The Template Method pattern
The Template Method pattern is a GoF behavioral pattern that uses inheritance to share code between the base class and its subclasses. It is another 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
First, we need to define a base class that contains the TemplateMethod
method and then define 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 12.1: Class diagram representing the Template Method pattern
How does this work?
AbstractClass
implements the shared code: the algorithm in itsTemplateMethod
methodConcreteClass
implements its specific part of the algorithm in its inherited...