Template Method Pattern in Java (with Example)
The Template Method pattern explained: define an algorithm's fixed skeleton in a base class and let subclasses fill in the varying steps. The Hollywood Principle, Template Method vs Strategy, Java code and UML.
🟠Design Patterns · Behavioral · Senior
The Template Method pattern defines the skeleton of an algorithm in a base class but lets subclasses fill in specific steps. Think of a recipe: the overall steps are fixed (prep → cook → serve), but what you cook varies. When several classes share the same overall flow yet differ in a few steps, Template Method removes the duplication while keeping each variation's unique bits.
The problem
You process data files: CSV, JSON, XML. Each follows the same flow — open the file, parse it, validate, save to DB, close. Only the parse step differs. If each processor is a separate class with the whole flow copy-pasted, you've duplicated the open/validate/save/close logic everywhere; fix a bug in "save" and you must fix it in all of them.
The solution: fix the skeleton, vary the steps
🟠Put the overall flow in a final template method in the base class; make the varying step abstract for subclasses to implement:
abstract class DataProcessor {
// the TEMPLATE METHOD — fixed skeleton, final so it can't be overridden
public final void process(String file) {
open(file);
Data d = parse(file); // ← the step that varies
validate(d);
save(d);
close();
}
protected abstract Data parse(String file); // subclasses fill this in
private void open(String f){ /* shared */ }
private void validate(Data d){ /* shared */ }
private void save(Data d){ /* shared */ }
private void close(){ /* shared */ }
}
class CsvProcessor extends DataProcessor {
protected Data parse(String f){ /* CSV-specific parsing */ return null; }
}
class JsonProcessor extends DataProcessor {
protected Data parse(String f){ /* JSON-specific parsing */ return null; }
}
The flow lives in one place; each subclass supplies only its unique parse(). Fix "save" once and every processor benefits. New format? New subclass overriding one method.
The Hollywood Principle
🟠Template Method embodies "Don't call us, we'll call you" — the base class controls the flow and calls down into the subclass's steps, rather than the subclass driving. This inversion of control is the key idea, and naming it is a strong senior signal. (Optional "hook" methods — empty by default — let subclasses optionally tweak extra points in the flow.)
Template Method vs Strategy
🟠Both let you vary part of a behaviour, but the mechanism differs: Template Method uses inheritance (subclass overrides steps of a fixed skeleton), while Strategy uses composition (swap a whole algorithm object at runtime). Template Method varies steps within one algorithm at compile time; Strategy swaps the entire algorithm at runtime. Mentioning that trade-off shows depth.
Where you meet it
Everywhere in frameworks: HttpServlet's service() calls your doGet()/doPost(); JUnit calls setUp() → your test → tearDown(); Spring's template classes (JdbcTemplate) run boilerplate and call your callback; Collections.sort calls your compareTo. Any framework that runs a fixed process and calls your code at defined points is using Template Method.
When to use it
Use it when several variants share the same overall algorithm but differ in a few steps, and you want to avoid duplicating the shared structure. If the variation is a whole interchangeable algorithm chosen at runtime, prefer Strategy; if there's no shared skeleton, this pattern doesn't apply.
The interview-ready summary
"Template Method puts an algorithm's fixed skeleton in a base-class method (usually final) and defers the varying steps to subclasses via abstract methods — so shared structure lives in one place and subclasses override only their differences. It follows the Hollywood Principle ('don't call us, we'll call you') — the base class drives and calls down into subclass steps. Unlike Strategy (composition, swap whole algorithm at runtime), it uses inheritance to vary steps. Real examples: HttpServlet, JUnit's setUp/tearDown, JdbcTemplate." That's it, with the Strategy contrast and Hollywood Principle."
What to read next
- Chain of Responsibility — the last pattern in this series
- Strategy Pattern — the composition-based alternative
- All Design Patterns (hub)
- ← The complete System Design guide (hub)