creational
Template Method
Define the skeleton of an algorithm in a base class, deferring specific steps to subclasses.
Several processes share a shape. Importing CSV, XML and JSON all mean: open the file, read it, validate, save, close.
Only the reading step really differs. But if you write each importer separately, you copy the other four steps three times. Fix a bug in one and you must remember the others.
Template Method puts the fixed order in a base class and lets subclasses fill in only the parts that vary.
A recipe — the process is always prep → cook → plate. What you prep, cook, and plate varies by dish.
Key Concepts
1
The base class has one method that runs the steps in order. This is the template method, and it is usually final so subclasses cannot change the sequence.
final
2
Steps that are always the same are implemented in the base class. Steps that differ are abstract, and each subclass supplies its own version.
3
You can also add optional hooks: methods with an empty default body that subclasses may override if they need to.
4
The trade-off is that this uses inheritance, so a subclass is tied to its parent. Strategy solves a similar problem with composition, which is more flexible.
When to use it
- Multiple classes share the same algorithm flow
- Enforce a fixed sequence of operations
- Framework lifecycle design
Watch out for
- Uses inheritance with fixed structure. Prefer Strategy when the full algorithm varies.
java
public abstract class DataMiner {
public final void mine(String path) {
openFile(path);
String raw = extractData();
String[] parsed = parseData(raw);
analyzeData(parsed);
closeFile();
}
protected abstract void openFile(String path);
protected abstract String extractData();
protected abstract void closeFile();
protected String[] parseData(String raw) { return raw.split("\n"); }
protected void analyzeData(String[] data) { System.out.println(data.length); }
}