Design Patterns: Template Method
I was recently installing a couple of storm doors on the house we live in. The door was not sold with a handle, you have to buy the handle separately which is nice because it allows one to choose from a few different styles and finishes. On top of that, the doors were not sold as either “left-hand” or “right-hand”… meaning that if you would actually like a functioning door, you have to drill a hole for the handle on one side of the door or the other, and place the hinge on one side or the other.
Pretty versatile door setup. We’re pretty happy with both doors.
The directions were very well written. Most of the steps for assembling and attaching the door to its frame fit on one page. There was a separate page included that on one side had the specific directions for a “left-open” door and on the other side had directions for a “right-open” door.
The main directions page was too abstract to install the door. But it did contain all of the same shared steps which meant that the company did not have to print redundant directions for both installations.
How does that relate to the template method pattern?
The Template method pattern is any time when a “Fill in the blanks” kind of solution can take place.
Meaning that essentially a generic algorithm gets defined in a parent class where most of the steps are sort of worked out. But then child classes “Fill in the blanks” in a way that is important for them.
Most of the steps are defined in the parent, but then children can change parts as needed.
This is especially useful for design time deviations in the algorithm.
To illustrate this example, some ruby code…
This may not be the best example, however, I write in my off time and hopefully can be forgiven the contrived example, any structural concerns, or lack of tests..
then run the file
This should generate an index.html
Open it in your favorite browser
You should see something like this…