Template method
A template method is a method in a superclass that fixes the order of steps and calls overridable hooks for the parts that vary. Subclasses fill in the hooks, not the skeleton.
Detailed Explanation
A job always logs start, runs work, logs end. If each subclass writes that sequence, one of them will forget the log. A final void run() in the abstract class calls logStart(), doWork(), logEnd(). doWork is abstract. Subclasses cannot skip the logs.
The skeleton is the template. The hooks are protected methods. Some hooks have default empty bodies (optional steps). final on the template prevents a subclass from replacing the sequence.
This is inheritance-heavy. Modern Java often prefers a strategy passed into a concrete class, or a default method on an interface. Template method still fits when the sequence is a safety rule (transactions: begin, work, commit/rollback) and you own the hierarchy.
AbstractList uses template method: get and size are abstract; indexOf is written in terms of them. InputStream.read(byte[]) is a template over read().
You reach for it when the order is the invariant and the steps are the variation. You reach for strategy when the whole algorithm is swapped. You reach for a decorator when you wrap an existing object.
The cost is a rigid hierarchy and the fragile-base-class problem: changing the template order breaks every subclass. Keep hooks few and documented. Do not call abstract hooks from the abstract constructor; the subclass fields are not ready.
Over-using template method produces deep abstract stacks. Prefer composition if you only share one helper.
A template method is a promise about order. Write that order in the method name or in a one-line comment at the top of run(). When a new step appears (metrics, a timeout), add it to the template once. If subclasses start copying the template to skip a step, the step was not really required, or the hierarchy is the wrong tool. At that point, extract a strategy for the optional step and keep the skeleton.
Code Examples
abstract class Job {
public final void run() {
System.out.println("start");
work();
System.out.println("end");
}
protected abstract void work();
}
class Ping extends Job {
@Override
protected void work() {
System.out.println("pong");
}
public static void main(String[] args) {
new Ping().run();
// prints:
// start
// pong
// end
}
}Common Gotchas
Deep abstract trees are hard to debug
flatten or compose.
Calling hooks from the abstract constructor reads unset subclass fields
Calling hooks from the abstract constructor reads unset subclass fields
A non-`final` template can be overridden and skip your safety steps
A non-`final` template can be overridden and skip your safety steps