Implementing the Template Method pattern
The Template Method is a GoF behavioral pattern that uses inheritance to share code between the base class and its subclasses. It is a very powerful, yet simple, design pattern.
Goal
The goal of the Template Method pattern is to encapsulate the outline of an algorithm in a base class while leaving some parts of that algorithm open for modification by the subclasses, which adds flexibility at a low cost.
Design
As mentioned earlier, the design is simple but extensible. First, we need to define a base class that contains the TemplateMethod()
method and then defines one or more sub-operations that need to be implemented by its subclasses (abstract
), or that can be overridden (virtual
).
Using UML, it looks like this:
Figure 10.1: Class diagram representing the Template Method pattern
How does this work?
AbstractClass
implements the shared code: the algorithm.ConcreteClass
implements its specific...