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.

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

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.
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); }
}