Behavioral 5 — Template Method
In one line
Define the skeleton of an algorithm in a base class, let subclasses fill in specific steps — inversion of control inside one class hierarchy.
Think of it like this
A recipe for making tea. The steps are always boil water → add tea → add milk/sugar → pour. Green tea and masala tea change only a step or two; the order stays the same.
Key ideas
- 01
Solves: repeated algorithm with only a few steps varying (cooking recipe, order validation, import pipelines).
- 02
Base: protected abstract steps; final public orchestrator that calls them.
- 03
Hollywood principle: 'don't call us, we'll call you'.
Java / Spring map
- →
AbstractList, InputStream (read() vs read(byte[])), Spring's JdbcTemplate.execute flow.
Code & diagrams
Data import pipeline — steps vary, order does not.
public abstract class DataImporter {
public final void run(Path src) { // skeleton — final, not overridable
try (InputStream in = open(src)) {
List<Row> rows = parse(in);
List<Row> valid = rows.stream().filter(this::isValid).toList();
persist(valid);
notify(valid.size());
} catch (IOException e) { onFailure(e); }
}
protected abstract InputStream open(Path p) throws IOException;
protected abstract List<Row> parse(InputStream in);
protected boolean isValid(Row r) { return true; } // hook — optional override
protected abstract void persist(List<Row> rows);
protected void notify(int n) { /* default no-op */ }
protected void onFailure(IOException e) { throw new UncheckedIOException(e); }
}Explain without notes
What is a 'hook' method vs an abstract method here?
Practice
Implement CsvImporter and JsonImporter with shared skeleton.
Trade-offs
- ↔
Inheritance lock-in: adding a step later means touching the base class. If steps vary independently, pass Strategy objects instead.
Completion checklist
I can write a final skeleton method with abstract steps and optional hooks.