Back to All Design Patterns
Pattern 14 of 22
Behavioral PatternBEGINNER6 min deep dive
Template Method Pattern
Defines the skeleton of an algorithm in the superclass but lets subclasses override specific steps of the algorithm without changing its structure.
Real-World Mental Model / Metaphor:
Building a prefabricated house. The master architectural blueprint defines the sequence: 1. Lay Foundation -> 2. Build Walls -> 3. Add Roof. Subclasses choose whether walls are wooden, brick, or glass.
Interactive Runtime Simulator
Test and tweak inputs dynamicallyInteractive Template Method SimulatorLIVE PLAYGROUND
Interact with the controls below to see how this design pattern executes in memory at runtime.
Configure Chain Handlers (Toggle Failures):
CHAIN PIPELINE STATUS
Step 1: AuthHandler.check() -> PASSED
Step 2: RateLimitHandler.check() -> PASSED
Step 3: PayloadGuard.check() -> PASSED
The Problem It Solves
Code duplication across subclasses that perform nearly identical algorithms with only minor step differences.
The Architectural Solution
Declare a `final` template method in the abstract base class that calls a series of abstract or hook methods implemented by subclasses.
Pattern Structure & Participants
| Participant | Role & Responsibility | Type |
|---|---|---|
| AbstractClass | Defines templateMethod() and abstract primitive steps | class |
| ConcreteClassA / B | Overrides primitive steps to customize behavior | class |
Collaboration Rules:
- Template method is final: cannot be overridden
- Subclasses supply custom step implementations
Production Code Implementation
Template Method.java
public abstract class DataMiner {
// The Template Method (final prevents overriding the sequence!)
public final void mineData(String path) {
openFile(path);
extractData();
parseData();
hookAfterParse(); // Optional hook
closeFile();
}
protected abstract void openFile(String path);
protected abstract void extractData();
protected abstract void parseData();
// Default Hook Method
protected void hookAfterParse() {}
private void closeFile() {
System.out.println("File stream safely closed.");
}
}
public class PdfDataMiner extends DataMiner {
protected void openFile(String path) { System.out.println("Opening PDF byte stream: " + path); }
protected void extractData() { System.out.println("Extracting PDF text layers and vector glyphs"); }
protected void parseData() { System.out.println("Parsing extracted PDF text into schema"); }
}
public class CsvDataMiner extends DataMiner {
protected void openFile(String path) { System.out.println("Opening CSV text reader: " + path); }
protected void extractData() { System.out.println("Reading comma-separated rows"); }
protected void parseData() { System.out.println("Parsing columns into DTO objects"); }
} When to Use:
- •When you want to let clients extend only particular steps of an algorithm, but not the whole algorithm or its structure.
- •When you have several classes that contain almost identical algorithms with some minor differences.
When to Avoid (Anti-Pattern):
- •When the algorithm skeleton itself needs to vary significantly across implementations.
Staff Engineering Interview Insights & Gotchas
- Explain the 'Hollywood Principle': 'Don't call us, we'll call you' (the superclass calls subclass methods, not vice versa).
- Mention Spring's `JdbcTemplate` as a classic enterprise template pattern.