A template method defines the program skeleton of an algorithm.
One or more of the algorithm steps can be overridden by subclasses to allow differing behaviors while ensuring that the overarching algorithm is still followed.
In object-oriented programming, first a class is created that provides the basic steps of an algorithm design. These steps are implemented using abstract methods. Later on, subclasses change the abstract methods to implement real actions. Thus the general algorithm is saved in one place but the concrete steps may be changed by the subclasses.
The template method thus manages the larger picture of task semantics, and more refined implementation details of selection and sequence of methods. This larger picture calls abstract and non-abstract methods for the task at hand. The non-abstract methods are completely controlled by the template method but the abstract methods, implemented in subclasses, provide the pattern’s expressive power and degree of freedom. Some or all of the abstract methods can be specialized in a subclass, allowing the writer of the subclass to provide particular behavior with minimal modifications to the larger semantics. The template method (which is non-abstract) remains unchanged in this pattern, ensuring that the subordinate non-abstract methods and abstract methods are called in the originally intended sequence.
The template method is used to:
- let subclasses implement (through method overriding) behavior that can vary
- avoid duplication in the code: the general workflow structure is implemented once in the abstract class’s algorithm, and necessary variations are implemented in each of the subclasses.
- control at what point(s) subclassing is allowed. As opposed to a simple polymorphic override, where the base method would be entirely rewritten allowing radical change to the workflow, only the specific details of the workflow are allowed to change.
- The control structure (inversion of control) that is the result of the application of a template pattern is often referred to as the Hollywood Principle: “Don’t call us, we’ll call you.” Using this principle, the template method in a parent class controls the overall process by calling subclass methods as required.
Create abstract glass:
Now extend this class in order to implement actual games: