Template Method
Category
Behavioral pattern
Problem
Define the skeleton of an algorithm in a base class, allowing subclasses to override specific steps without changing the algorithm’s structure. Useful when multiple classes share the same algorithm structure but differ in specific steps.
Solution
- Define an abstract base class with a template method that defines the algorithm structure
- The template method calls abstract or hook methods for the variable steps
- Subclasses implement the abstract methods to customize specific steps
Structure
- AbstractClass: Defines the template method and abstract/hook methods
- ConcreteClass: Implements the abstract methods
Key Benefits
- Code reuse — Common algorithm structure is defined once in the base class
- Extensibility — Subclasses can override specific steps without changing the overall structure
- Inversion of control — Base class controls the algorithm; subclasses provide the details
Trade-offs
- Inversion of control — Subclasses must follow the template method’s structure
- Complexity — Can become hard to understand when the template method is complex
When to Use
- You want to avoid code duplication in similar algorithms
- You want to control the overall algorithm structure while allowing subclasses to customize steps
- You want to extract common behavior into a single class
Examples
- Java
- Spring Framework
,post(),form_valid()`) - Ruby On Rails is the template method)
- ETL pipeline frameworks (extract, transform, load steps as hooks)