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.
What the interviewer is probing.
1. "What does Template Method define?" *Probing:* the purpose. *Stalls:* "A template." *Moves up:* the skeleton of an algorithm in a base method, deferring specific steps to subclasses without letting them change the order.
2. "How does it compare with Strategy?" *Probing:* the comparison. *Stalls:* "They are the same." *Moves up:* Template Method varies steps through inheritance at compile time; Strategy swaps the whole algorithm through composition at runtime.
3. "What is a hook method?" *Probing:* the detail. *Stalls:* "An override." *Moves up:* an optional step with an empty or default implementation a subclass may override — unlike an abstract step it must.
4. "What is the criticism?" *Probing:* honesty. *Stalls:* "None." *Moves up:* inheritance couples subclasses to the base class, so a base change ripples — composition is usually preferred now.
A recipe — the process is always prep → cook → plate. What you prep, cook, and plate varies by dish.
Key Concepts
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); }
}