The Template Method Design Pattern is a behavioral design pattern that defines the skeleton of an algorithm in a base class but allows subclasses to override specific steps of the algorithm without changing its structure.
Intent
- Define the framework of an algorithm in a base class.
- Allow subclasses to provide specific implementations for one or more steps of the algorithm.
Key Concepts
- Base Class (Template):
- Contains the template method that defines the sequence of steps in an algorithm.
- Implements some of the steps directly and defines placeholders (abstract or virtual methods) for steps that need to be customized.
- Concrete Subclasses:
- Implement the abstract or virtual steps of the algorithm.
- Can override certain steps while adhering to the overall structure.
When to Use
- When multiple classes share the same overall behavior but differ in specific steps.
- To enforce a common structure for algorithms while allowing flexibility in implementation.
- When you want to promote code reuse and avoid duplicating common logic.