Implementing the Template Method pattern
The Template Method is a GoF behavioral pattern using 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.
Design
As mentioned earlier, the design is simple but extensible. First, we need to define a base class that contains the TemplateMethod()
, 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:
AbstractClass
implements the shared code: the algorithm.ConcreteClass
implements its specific part of the algorithm.Client
calls...