Template Method
Defining an algorithm's skeleton in a base class and letting subclasses fill in steps — hooks, the Hollywood principle, framework examples, and replacing inheritance with composition.
Intent: define the skeleton of an algorithm in a method, deferring some steps to subclasses. Subclasses redefine certain steps without changing the algorithm's structure.
Example: every data import does the same thing — open the source, read records, validate, transform, save, report — but reading CSV differs from reading JSON or an API.
open()— abstract: each subclass knows its sourceread()— abstractvalidate(record)— hook: default accepts everything; subclasses may overridetransform(record)— abstractsave(records)— fixed in the base classreport()— fixed
public abstract class DataImporter {
// The template method: final so subclasses can't change the sequence
public final ImportReport run() {
open();
List<Record> valid = new ArrayList<>();
int rejected = 0;
for (RawRecord raw : read()) {
if (validate(raw)) valid.add(transform(raw));
else rejected++;
}
save(valid);
close();
return new ImportReport(valid.size(), rejected);
}
protected abstract void open(); // required steps
protected abstract Iterable<RawRecord> read();
protected abstract Record transform(RawRecord raw);
protected boolean validate(RawRecord raw) { return true; } // hook: optional override
protected void close() {} // hook
private void save(List<Record> records) { repository.saveAll(records); } // fixed
}
public class CsvImporter extends DataImporter {
private final Path path; private BufferedReader reader;
public CsvImporter(Path path) { this.path = path; }
protected void open() { reader = Files.newBufferedReader(path); }
protected Iterable<RawRecord> read() { return () -> reader.lines().skip(1).map(RawRecord::fromCsv).iterator(); }
protected Record transform(RawRecord r) { return new Record(r.get(0), Double.parseDouble(r.get(1))); }
@Override protected boolean validate(RawRecord r) { return r.size() == 2; }
@Override protected void close() { try { reader.close(); } catch (IOException ignored) {} }
}from abc import ABC, abstractmethod
class DataImporter(ABC):
def run(self) -> dict: # template method
self.open()
valid, rejected = [], 0
for raw in self.read():
if self.validate(raw):
valid.append(self.transform(raw))
else:
rejected += 1
self._save(valid)
self.close()
return {"imported": len(valid), "rejected": rejected}
@abstractmethod
def open(self): ...
@abstractmethod
def read(self): ...
@abstractmethod
def transform(self, raw): ...
def validate(self, raw) -> bool: # hook
return True
def close(self): ... # hook
def _save(self, records):
repository.save_all(records)
class CsvImporter(DataImporter):
def __init__(self, path): self.path = path
def open(self): self.f = open(self.path, newline="")
def read(self): return csv.DictReader(self.f)
def validate(self, raw): return raw.get("amount", "").strip() != ""
def transform(self, raw): return Record(raw["id"], float(raw["amount"]))
def close(self): self.f.close()abstract class DataImporter {
async run() { // template method
await this.open();
const valid: Rec[] = [];
let rejected = 0;
for await (const raw of this.read()) {
if (this.validate(raw)) valid.push(this.transform(raw));
else rejected++;
}
await repository.saveAll(valid);
await this.close();
return { imported: valid.length, rejected };
}
protected abstract open(): Promise<void>;
protected abstract read(): AsyncIterable<Raw>;
protected abstract transform(raw: Raw): Rec;
protected validate(_raw: Raw): boolean { return true; } // hook
protected async close(): Promise<void> {} // hook
}
class JsonApiImporter extends DataImporter {
private items: Raw[] = [];
protected async open() { this.items = await (await fetch(this.url)).json(); }
protected async *read() { yield* this.items; }
protected transform(r: Raw) { return { id: r.id, amount: Number(r.total) }; }
constructor(private url: string) { super(); }
}The Hollywood principle
"Don't call us, we'll call you." The base class controls the flow and calls the subclass's steps — not the other way round. This inversion of control is the essence of frameworks:
| Framework | Template | You fill in |
|---|---|---|
| JUnit / pytest | Test lifecycle | setUp, test method, tearDown |
| Servlets | HttpServlet.service() | doGet, doPost |
| React class components | Render lifecycle | render, componentDidMount |
| Java collections | AbstractList | get(i) and size() — iteration, contains, etc. come free |
| Android | Activity lifecycle | onCreate, onResume |
| Spring | JdbcTemplate | A callback that maps rows |
Template method vs strategy
The same goal — vary steps of an algorithm — with different mechanisms:
- Varying steps are overridden methods in subclasses
- Chosen at compile time by picking a subclass
- Simple when there's one natural axis of variation
- Couples subclasses to the base class
- Varying steps are objects or functions passed in
- Can be swapped at runtime and mixed freely
- Easier to test each piece in isolation
- Modern APIs often prefer this:
JdbcTemplate.query(sql, rowMapper)
# Same importer with composition: steps are passed in
def run_import(read, transform, validate=lambda r: True):
records = [transform(r) for r in read() if validate(r)]
repository.save_all(records)- Template Method fixes the algorithm's skeleton in a base class; subclasses fill in steps.
- Abstract steps are required; hooks are optional overrides with defaults.
- Make the template method final so the sequence can't be broken.
- It's the Hollywood principle behind most frameworks.
- Passing functions (strategy) is the composition-based alternative.