# Purpose
The Template Method pattern defines the skeleton of an algorithm in an operation, deferring some steps to subclasses.
# Problem
-
Redundancy: Repetition of common logic across multiple classes processing nearly identical flows.
-
Fragility: Difficulty ensuring that all variants follow the same control steps.
# Solution
Create a base class with a final method (the template) that invokes abstract methods. Subclasses fill in the blanks without changing the flow.
# Structure
# Participants
- AbstractClass: Defines the template and base steps.
- ConcreteClass: Implements specific steps of the algorithm.
# When to Use It
When you have a fixed recipe for a process but ingredients that change based on context or product type.
# Advantages
-
verified
DRY: Centralizes common code in the superclass.
-
verified
Control: The algorithm's structure is immutable in subclasses.
# Disadvantages
-
warning
Rigidity: Subclasses are tied to the base class structure.
-
warning
LSP: Risk of violating the substitution principle if not implemented carefully.
# Example: Drink Preparation
Common steps for Tea and Coffee (Boil, Pour) but specific preparation and ingredients for each.
# Java Code
abstract class DrinkTemplate {
final void prepare() { boil(); brew(); pour(); }
abstract void brew();
void boil() { System.out.println("Boiling water"); }
void pour() { System.out.println("Pouring into cup"); }
}
class Coffee extends DrinkTemplate {
void brew() { System.out.println("Brewing coffee grounds"); }
}
class Tea extends DrinkTemplate {
void brew() { System.out.println("Steeping the tea bag"); }
}
# Mapping Participants
- DrinkTemplate: AbstractClass.
- Tea/Coffee: ConcreteClasses.
- Client: Uses the DrinkTemplate's prepare method.
# Conclusions
Ensures that all subtypes of a process follow the same protocol, allowing clean and centralized specializations.
# Related Patterns
Factory Method
Often used within a Template Method to instantiate objects.
Strategy
Template Method varies parts with inheritance, Strategy varies the entire algorithm with delegation.