Template Method
24 Mar 2022Intent
Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.
Applicability
The Template pattern should be used:
- To implement the invariant parts of an algorithm once and leave it up to subclasses to implement the behavior that can vary.
- when common behavior among subclasses should be factored and localized in a common class to avoid code duplication.
- to control subclasses extensions. You can define a template method that calls "hook" operations at specific points, thereby permitting extensions only at those points.
Structure
Participants
- AbstractClass: defines abstract primitive operations that concrete subclasses define to implement steps of an algorithm, implements a template method defining the skeleton of an algorithm.
- ConcreteClass: implements the primitive operations to carry out subclass-specific steps of the algorithm.
Collaborations
ConcreteClass relies on AbstractClass to implement the invariant steps of the algorithm.
Sample Code
Related Patterns
- Factory Methods are often called by template methods.
- Strategy: Template methods use inheritance to vary part of an algorithm. Strategies use delegation to vary the entire algorithm.