Design Patterns - Behavioral

Template Method Pattern

Define the skeleton of an algorithm in the base class, letting subclasses override specific steps without changing the overall structure.

10 min readEssential

1What is the Template Method Pattern?

Real-World Analogy
Building a House

Every house follows the same construction steps: foundation, walls, roof, finishing. The steps are fixed, but each house can use different materials (wood vs brick) and styles for each step.

Making Tea/Coffee

Both follow: boil water, brew, pour, add condiments. The algorithm is the same, but brewing tea vs coffee differs. Subclasses customize specific steps.

Template Method Pattern defines the skeleton of an algorithm in a base class method (the template), deferring some steps to subclasses. It lets subclasses redefine certain steps without changing the algorithm's structure.

Template Method Structure

AbstractClass
templateMethod() - final
step1(); step2(); step3();
abstract step1()
abstract step2()
step3() // hook with default
extends
ConcreteA
step1(): impl A
step2(): impl A
ConcreteB
step1(): impl B
step2(): impl B

2Key Concepts

Template Method
The main method in base class that defines the algorithm skeleton. Usually marked final to prevent override. Calls abstract/hook methods.
Abstract Methods
Steps that MUST be implemented by subclasses. These are the varying parts of the algorithm that differ between implementations.
Hook Methods
Optional steps with default (often empty) implementation. Subclasses CAN override if needed. Provides flexibility.
Hollywood Principle
"Don't call us, we'll call you." Base class calls subclass methods, not the other way around. Inverts control.

3Implementation

Data mining application that processes different file formats:

Data Mining - Template Method
// ========== Abstract Class with Template Method ==========
abstract class DataMiner {

    // Template Method - defines the algorithm skeleton
    // Marked final to prevent subclasses from changing the flow
    public final void mine(String path) {
        openFile(path);
        extractData();
        parseData();
        analyzeData();
        sendReport();
        closeFile();
    }

    // Abstract methods - MUST be implemented
    protected abstract void openFile(String path);
    protected abstract void extractData();
    protected abstract void parseData();
    protected abstract void closeFile();

    // Hook methods - CAN be overridden (have default implementation)
    protected void analyzeData() {
        System.out.println("Performing standard analysis...");
    }

    protected void sendReport() {
        System.out.println("Sending report via email...");
    }
}

// ========== Concrete Implementation - PDF ==========
class PDFMiner extends DataMiner {
    @Override
    protected void openFile(String path) {
        System.out.println("Opening PDF file: " + path);
    }

    @Override
    protected void extractData() {
        System.out.println("Extracting text from PDF pages...");
    }

    @Override
    protected void parseData() {
        System.out.println("Parsing PDF data structures...");
    }

    @Override
    protected void closeFile() {
        System.out.println("Closing PDF reader.");
    }

    // Override hook to customize
    @Override
    protected void sendReport() {
        System.out.println("Sending PDF report via Slack...");
    }
}

// ========== Concrete Implementation - CSV ==========
class CSVMiner extends DataMiner {
    @Override
    protected void openFile(String path) {
        System.out.println("Opening CSV file: " + path);
    }

    @Override
    protected void extractData() {
        System.out.println("Reading CSV rows...");
    }

    @Override
    protected void parseData() {
        System.out.println("Parsing CSV columns...");
    }

    @Override
    protected void closeFile() {
        System.out.println("Closing CSV reader.");
    }
    // Uses default analyzeData and sendReport
}

// ========== Usage ==========
public class Main {
    public static void main(String[] args) {
        DataMiner pdfMiner = new PDFMiner();
        pdfMiner.mine("report.pdf");

        System.out.println();

        DataMiner csvMiner = new CSVMiner();
        csvMiner.mine("data.csv");
    }
}
Output:
Opening PDF file: report.pdf
Extracting text from PDF pages...
Parsing PDF data structures...
Performing standard analysis...
Sending PDF report via Slack...
Closing PDF reader.

Opening CSV file: data.csv
Reading CSV rows...
Parsing CSV columns...
Performing standard analysis...
Sending report via email...
Closing CSV reader.

4Template Method vs Strategy

AspectTemplate MethodStrategy
MechanismInheritanceComposition
VariesParts of algorithmEntire algorithm
When to chooseCompile-timeRuntime
ControlBase class controlsClient controls

5Interview Questions

What is the Template Method pattern?
Template Method defines the skeleton of an algorithm in a base class, with some steps deferred to subclasses. The base class controls the flow (template method) while subclasses provide specific implementations for abstract steps. Hook methods provide optional customization points.
What is the Hollywood Principle?
'Don\\'t call us, we\\'ll call you.' In Template Method, the base class calls subclass methods, not vice versa. Subclasses don\\'t control the algorithm flow - they just provide implementations that the base class calls at the right time.
When would you use Template Method vs Strategy?
Use Template Method when: 1) Algorithm structure is fixed but steps vary, 2) You want to enforce a specific sequence. Use Strategy when: 1) You want to swap entire algorithms at runtime, 2) Algorithms are independent and interchangeable. Template Method = inheritance, Strategy = composition.

6Key Takeaways

1Template Method defines algorithm skeleton in base class.
2Subclasses implement abstract methods for varying steps.
3Hook methods provide optional customization with defaults.
4Base class controls flow (Hollywood Principle).
5Uses inheritance; Strategy uses composition.
6Common in frameworks (JUnit setUp/tearDown, servlet lifecycle).