3.11 Template Method
The Template Method pattern defines the skeleton of an algorithm in a base class, deferring some steps to subclasses. The overall structure stays fixed; only the varying steps are filled in by subclasses — hence the "Hollywood Principle": don't call us, we'll call you (the base calls the subclass, not the other way around).
Brewing tea and coffee is almost the same flow: boil water → brew → pour → add condiments. Only "brew" and "add condiments" differ. The lab below lets you switch tea/coffee and see which steps share the skeleton and which are overridden.
Fixed skeleton, open steps
abstract class Beverage {
// template method: lock the step order with final
public final void prepare() {
boilWater();
brew(); // abstract step
pourInCup();
addCondiments(); // abstract step
}
private void boilWater() { /* shared */ }
private void pourInCup() { /* shared */ }
protected abstract void brew();
protected abstract void addCondiments();
}prepare() is declared final, so subclasses can't change the step order — they only fill in the steps declared abstract. This keeps the algorithm skeleton stable.
Hook methods: optional intervention points
Besides abstract steps, a template method can offer hooks — the base gives a default (often empty) implementation that subclasses may optionally override:
protected boolean customerWantsCondiments() { return true; } // hookThe data-pipeline lab below lets you toggle the "validate" and "format" hooks, watching the fixed steps always run while optional hooks engage on demand — and the order never changes.
Tradeoffs
- Benefits: eliminate a duplicated algorithm skeleton, lifting the common flow to the base and leaving differences to subclasses.
- Cost: it relies on inheritance and is less flexible than Strategy (compile-time binding, single-inheritance limits). When you need to swap whole algorithms at runtime, Strategy fits better; when several variants share a large skeleton and differ in a few steps, Template Method is more natural.
Many framework "lifecycle callbacks" (like onCreate, render, or a test's setUp/tearDown) are template methods at heart.