How would you implement the Template Method pattern in Java?

The Template Method pattern is implemented by defining a final method in an abstract base class that fixes the sequence of steps in an algorithm, while individual steps are delegated to abstract or overridable methods that subclasses implement.

Key Points: • The base class declares a final (or non-overridable) template method containing the fixed step order. • Steps that must vary by subclass are declared abstract; steps with sensible defaults can be regular or protected methods. • Optional steps can be implemented as "hook" methods with empty default bodies that subclasses override only if needed. • Subclasses only override the varying steps, never the template method itself, which preserves the overall algorithm structure. • Making the template method final prevents subclasses from accidentally breaking the intended step order.

Example: A ReportGenerator base class can define generate() as fetchData() → formatData() → exportReport(), with PdfReportGenerator and ExcelReportGenerator only overriding exportReport().

Code Example:

abstract class DataProcessor {

    public final void process() {
        readData();
        parseData();
        saveData();
    }

    protected abstract void readData();
    protected abstract void parseData();

    protected void saveData() {
        System.out.println("Saving processed data");
    }
}

class CsvDataProcessor extends DataProcessor {
    protected void readData() { System.out.println("Reading CSV"); }
    protected void parseData() { System.out.println("Parsing CSV"); }
}

Interview Tip: A concise interview answer is:

"I put the fixed algorithm sequence in a final method on an abstract base class, and expose the steps that vary as abstract methods for subclasses to implement. Making the template method final keeps subclasses from reordering or skipping steps, so the overall process stays consistent while the details change per subclass."