Template Method
Beginner · 12 min read · Low-Level Design, Behavioral Patterns
A fixed algorithm skeleton with overridable steps.
The idea in plain words
A process always runs the same steps in the same order, but one or two steps differ. Write the order of steps once in a base class, and let subclasses fill in only the steps that change.
The problem
You import data files from several partners — CSV from one, JSON from another, XML from a third. Each importer does the same thing in the same order: open the source, parse records, validate them, transform to your model, save, and report. Only parsing (and sometimes validation) differs.
The solution
Put the invariant sequence in a final method of an abstract base class; make the varying steps abstract (or overridable hooks).
The Hollywood Principle
The base class controls the flow and calls subclass methods at the right moments — the opposite of a subclass calling library code. This inversion is how frameworks work: you fill in steps; the framework decides when they run.
Where you've seen it
Template Method vs Strategy
Modern Java often prefers the callback form — pass the varying step as a lambda:
Pros and cons
Interview questions
- Why should the template method be final?
- When would you prefer Strategy over Template Method?
Further reading
Key takeaways
- Template Method fixes an algorithm's skeleton in a final base-class method and lets subclasses fill in steps.
- Steps can be abstract, default-implemented, or empty hooks.
- It embodies the Hollywood Principle and underpins frameworks.
- Prefer Strategy or callbacks for runtime or multi-dimensional variation.