What is the difference between Strategy and Template Method?
Answer
Both Strategy and Template Method encapsulate algorithms, but they do so differently. Template Method uses inheritance: the algorithm skeleton is fixed in the base class and subclasses override specific steps — the hook calls are built into the class hierarchy and cannot be changed at runtime. Strategy uses composition: the entire algorithm is encapsulated in a strategy object that is injected into the context and can be swapped at runtime. Template Method is simpler when you have one algorithm with a few variable steps. Strategy is more flexible, more testable, and preferred by modern design (favoring composition over inheritance). In practice, Strategy + dependency injection has largely superseded Template Method.
Previous
What is the difference between Observer and Mediator?
Next
What are the different types of Proxy?
More Design Patterns (Gang of Four) Questions
View all →- Intermediate What is the Template Method design pattern?
- Intermediate What is the Visitor design pattern?
- Intermediate What is the difference between Factory Method and Abstract Factory?
- Intermediate When should you NOT use design patterns?
- Intermediate How are the Gang of Four patterns categorized?