Cheatsheet
Template Method
Intent
Define the skeleton of an algorithm in one method and let subclasses redefine only some steps, without changing the order or the rest.
Structure (UML)
classDiagram
direction TB
class ResultImporter {
<<AbstractClass>>
+importAll(String payload) ImportReport
#parse(String payload)* List~Result~
#afterImport(ImportReport report) void
-validate(Result r)$ Optional~String~
}
class CsvResultImporter {
<<ConcreteClass>>
#parse(String payload) List~Result~
}
class JsonResultImporter {
<<ConcreteClass>>
#parse(String payload) List~Result~
#afterImport(ImportReport report) void
}
ResultImporter <|-- CsvResultImporter
ResultImporter <|-- JsonResultImporterParticipants
- AbstractClass (ResultImporter), with the template method importAll() and the shared steps
- Abstract steps (parse), which every subclass must implement
- Hooks (afterImport), optional steps that do nothing by default
- ConcreteClass (CsvResultImporter, JsonResultImporter), which only fill in what varies
ResultImporter.java
public final ImportReport importAll(String payload) {
List<Result> parsed = parse(payload); // 1. varies: CSV, JSON...
ImportReport report = tx.execute(status -> { // all rows or none
int imported = 0;
List<String> rejected = new ArrayList<>();
for (Result r : parsed) {
Optional<String> problem = validate(r); // 2. shared rule, written once
if (problem.isPresent()) {
rejected.add(r.athlete() + "/" + r.wod() + ": " + problem.get());
continue;
}
results.save(r); // 3. shared
imported++;
}
return new ImportReport(imported, rejected);
});
afterImport(report); // 4. hook: optional extra step
return report;
}
protected abstract List<Result> parse(String payload);
protected void afterImport(ImportReport report) {
// hook: does nothing unless a subclass needs it
}Pros
- Shared rules (validate, save, report) are written once
- A new format is a subclass with a single required method
- The order of the steps is guaranteed, because the template method is final
Cons
- It relies on inheritance, so the subclass is tied to the base class
- With many hooks it's hard to follow what runs and when
- If the variation grows a lot, a strategy or a callback usually fits better