Overview
The Template Method pattern defines the skeleton of an algorithm in a base class method and lets subclasses fill in specific steps. The template method itself is final: it calls steps in a fixed order, some implemented in the base class, some abstract, and some optional 'hooks' with default behavior.
It removes duplicated workflow code across similar classes, such as data importers that all open, parse, validate, save, and close, or games that all initialize, play turns, and announce a winner. Its main drawback is inheritance coupling; Strategy is the composition-based alternative.
Every bread follows the same steps: mix, knead, rise, shape, bake. The recipe fixes the order; each type of bread fills in ingredients and baking time.
When to use it
- Several classes share the same workflow but differ in some steps.
- You want to enforce step order.
- Framework extension points (lifecycle hooks).
Where it shows up in interviews
Recognize it when: similar classes repeat the same sequence.
- Design a data import pipeline (CSV, JSON, XML)
- Design report generators
- Design a board game framework
Where it is used in real software
Implements most List methods in terms of get() and size() that subclasses provide.
setUp/test/tearDown hooks follow a fixed template.
componentDidMount and friends are hooks called by a fixed rendering algorithm.
Key terms
- Template method
- Final method defining the step order.
- Primitive operation
- Abstract step subclasses must implement.
- Hook
- Optional step with default behavior.
- Hollywood principle
- 'Don't call us, we'll call you': the base calls subclass steps.
How it works, step by step
- 1Write the algorithm once
In the base class, as a final method.
- 2Mark varying steps abstract
parse(), transform().
- 3Provide hooks for optional steps
beforeSave() { }.
- 4Implement subclasses
Fill in the abstract steps only.
- 5Keep the template final
Subclasses cannot reorder steps.
Data importers
importFile(): read -> parse -> validate -> save -> report
| Step | Base class | CsvImporter | JsonImporter |
|---|---|---|---|
| read | Implemented | - | - |
| parse | Abstract | Split lines by commas | JSON.parse |
| validate | Implemented (common rules) | - | - |
| afterValidate (hook) | Default: nothing | Trim whitespace | - |
| save and report | Implemented | - | - |
NOWStep: read | Base class: Implemented | CsvImporter: - | JsonImporter: -
Each importer is a few lines; the workflow and its order are defined once.
Implementation
public abstract class DataImporter { // Template method: fixed order, cannot be overridden public final ImportReport importFile(Path path) throws IOException { String raw = Files.readString(path); List<Record> records = parse(raw); List<Record> valid = records.stream().filter(this::isValid).toList(); afterValidate(valid); save(valid); return new ImportReport(records.size(), valid.size()); } protected abstract List<Record> parse(String raw); // required step protected void afterValidate(List<Record> records) {} // hook private boolean isValid(Record r) { return r.id() != null && !r.id().isBlank(); } private void save(List<Record> records) { /* shared persistence */ }} public final class CsvImporter extends DataImporter { @Override protected List<Record> parse(String raw) { return raw.lines().skip(1).map(line -> line.split(",")) .map(cols -> new Record(cols[0], cols[1])).toList(); }}Complexity and performance
Subclasses fill steps.
Negligible.
Trade-offs
Subclasses depend on the base class; changes to the skeleton affect all of them.
Great for enforcing order; awkward when steps need to be combined differently.
Variants and related techniques
Pass step implementations as objects or functions to a workflow class.
Optional customization points reduce required overrides.
Common mistakes
- Template method not final.
Fix: Subclasses might reorder or skip steps; make it final.
- Too many abstract steps.
Fix: Provide defaults as hooks; keep required steps minimal.
Interview questions
Template Method vs Strategy?
Template Method varies parts of an algorithm through inheritance, with the base class controlling order. Strategy replaces the whole algorithm through composition and can change at runtime.
What is a hook method?
An optional step in the template with a default (often empty) implementation that subclasses may override to customize behavior.
Practice problems
| Problem | Difficulty | What it trains |
|---|---|---|
| Report generator for PDF and HTML | Easy | Skeleton and steps. |
| Board game framework (chess, checkers) | Medium | Turn loop. |