Part 5 of 6 · 2 min read
Compared with Strategy
Inheritance or composition.
Template Method or Strategy
The two patterns solve similar problems in opposite ways.
| Template Method | Strategy | |
|---|---|---|
| Mechanism | Inheritance | Composition |
| What varies | Single steps of one algorithm | The whole algorithm |
| When chosen | At compile time, by the subclass | At run time, by the client |
| Can it change while running | No | Yes |
| Risk | Fragile subclasses, constructor trap | More objects and wiring |
Modern designs often favour Strategy because composition is more flexible, as Level 1, module 4 argued. Template Method still has a place. It suits frameworks where the library owns the outline, such as a test runner calling setUp, then the test, then tearDown, or a servlet calling doGet. It also suits small hierarchies where the order of steps must never change.
A useful trick is to build the same thing with lambdas. The report can take its header and formatRow as functions, so no subclass is needed. Then the outline is in one class and the steps are passed in. In a design round, say which you chose and why.
Interview angle
Answer in your head first, then open it.
What is the Template Method pattern?
A parent class fixes the order of an algorithm in a method and calls steps that subclasses fill in.
What is the Hollywood principle?
The parent calls the subclass, and the subclass does not call the parent's algorithm. It is named after a film studio's habit of telling applicants to wait for the phone to ring.
Template Method or Strategy?
Template Method varies steps by inheritance at compile time. Strategy varies the whole algorithm by composition at run time.
Check yourself: 1. Which of the two can change behaviour while the program runs? 2. Name a framework that uses Template Method.
Words you will meet
| Word | Meaning |
|---|---|
| Template method | A method that fixes the order of steps |
| Hook | A step with a default body that may be overridden |
| Abstract step | A step that every subclass must supply |
| Hollywood principle | The parent calls the subclass, not the other way |
| Skeleton | The fixed outline of an algorithm |