Sometimes when designing applications you’ll come across a section that is constantly changing or being added on to. A tell tale sign of this is when you have a proliferation of if/then statements in a method that all follow the same general structure but for specific cases. That last sentence may not have made too much sense but here are a few examples:
- You have a payment system that takes in customer data and card info but you need specific steps for when a customer uses paypal vs stripe vs dwolla.
- You’re sending out an automated report but need to display the output using a variety of file types (html, json, xml).
The template method pattern is utilized by creating a base template (in Ruby’s case a parent class) and creating subclasses for differing scenarios that follow the base template.
##Here’s an example##
As you can see the huge benefit of the template method pattern is the avoidance of huge if/then or case statements within the base class. The template method also leaves us open to implement more games in the future, granted they loosely follow the same basic setup as defined in our template.
Basically, the template method pattern allows you to account for variations in your algorithms. The template class holds the skeleton of the algorithm while the subclasses perform their individual details.
If you know of an interesting example of the template method pattern being used in the wild, please comment below!