The Template Method pattern helps to create the skeleton of an algorithm. This skeleton provides one or many methods which can be altered by subclasses but which don’t change the algorithm’s structure.
The UML diagram for the Template Method is pretty simple. It has one abstract class with the TemplateMethod and one or many sub methods which can be overridden by subclasses. These sub methods can be either abstract or virtual. If they are abstract, they have to be implemented. If they are virtual, they can be overridden to alter the behavior of this step.
Implementation of the Template Method pattern
To be honest, the Template Method was pretty confusing to me in the beginning but after I tried to implement it, it became clear how it works. My implementation is pretty simple but it helped me to understand the pattern and I hope it helps you too.
I want to do some calculation and then save the result somewhere. The algorithm has three steps whereas step two and three can be overridden by a subclass. The class Calculator offers the TemplateMethod. This method contains the three steps.
The first step, BeforeCalculation can’t be overridden by the subclasses and therefore will always be executed. The second step of the algorithm, CalculateSomething can be overridden. The classes CalculatorOracle and CalculatorSqlAzure override this method and do their own calculations. The CalculatorSqlAzure also overrides the property Result.
The CalculatorOracle class only overrides the CalculateSomething method.
The third and last step, SaveResult is only overridden by the CalculatorSqlAzure class. This means that the CalculatorOracle class uses the method provided by the Calculator.
I know that this example is not really what you will see in a real-world project but I hope that it helped you to understand the Template Method pattern. You can find the source code on GitHub.
The Template Method pattern to achieve a clean design. The algorithm provided by the base class is closed for modification but is open for extension by subclasses. As a result, your design satisfies the open-closed principle. The pattern also helps to implement the Hollywood principle (“Don’t call us, we call you”).
One downside is that the steps of the algorithm must be already known when the pattern is applied. Therefore the Template Method pattern is great for reuse but it is not as flexible as for example the Strategy pattern.
Strategy: Inject a complete algorithm implementation into another module
Decorator: Compose an algorithm or behavior from several sub-parts
Factory: Define a common interface for creating new instances of types with many implementations
I showed how the Template Method pattern can be used to provide a skeleton for an algorithm. One or many parts of this algorithm can be overridden by subclasses. This behavior helps achieving the open-closed principle and therefore a clean overall design. I also implemented a simple example to show how the pattern works.