The Template Method Pattern: The Recipe for Success
Master the Template Method Pattern in Java. Learn how to define the skeleton of an algorithm in a superclass but let subclasses override specific steps.
Moshiour Rahman
Advertisement
The Problem: Copy-Paste Code
Imagine you are coding a data miner.
PDFMiner: Opens file, extract raw data, parses PDF, analyzes data, closes file.CSVMiner: Opens file, extract raw data, parses CSV, analyzes data, closes file.
Lines 1, 2, 4, 5 are identical. Only line 3 (Parsing) is different. If you copy-paste the whole method, you have code duplication. If you change the “Analyze” logic, you have to fix it in 20 places.
The Solution: The Template Method
The 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-Life Analogy: Cooking Pasta 🍝
The General Recipe (The Template):
- Boil Water.
- Add [Generic Pasta].
- Cook for [X Minutes].
- Drain.
- Add Sauce.
Steps 1, 4, 5 are the same for everyone. Steps 2, 3 vary depending on if you are making Spaghetti or Penne.
Visualizing the Pattern

Implementation
1. The Abstract Class (The Skeleton)
public abstract class DataMiner {
// This is the Template Method.
// It is 'final' so subclasses can't mess up the sequence.
public final void mine(String path) {
openFile(path);
extractData();
parseData(); // Concrete step
analyzeData();
closeFile();
}
// Concrete methods (shared logic)
private void openFile(String path) { System.out.println("Opening " + path); }
private void extractData() { System.out.println("Extracting raw bytes..."); }
private void analyzeData() { System.out.println("Analyzing semantics..."); }
private void closeFile() { System.out.println("Closing file."); }
// Abstract methods (Steps that MUST be customized)
protected abstract void parseData();
// Hooks (Optional steps)
protected void onMiningComplete() {}
}
2. The Concrete Subclasses (The Variables)
public class PDFMiner extends DataMiner {
@Override
protected void parseData() {
System.out.println("Parsing PDF structure...");
}
}
public class CSVMiner extends DataMiner {
@Override
protected void parseData() {
System.out.println("Parsing CSV delimiters...");
}
@Override
protected void onMiningComplete() {
System.out.println("CSV mined successfully!");
}
}
Usage
DataMiner pdf = new PDFMiner();
pdf.mine("document.pdf");
// Runs the shared skeleton, but invokes PDF parsing logic
DataMiner csv = new CSVMiner();
csv.mine("data.csv");
// Runs the shared skeleton, but invokes CSV parsing logic
In The Wild (Real World Examples)
1. Spring JdbcTemplate (Again?)
Wait, JdbcTemplate uses callbacks (Strategy), but pure Template Method is found in…
2. javax.servlet.http.HttpServlet
The service() method is the template. It checks the HTTP method and calls doGet(), doPost(), etc.
You override doGet(). You don’t rewrite the whole service() request dispatching logic. That’s Template Method.
Cheat Sheet
| Feature | Details |
|---|---|
| Category | Behavioral |
| Problem Solved | Code duplication in similar algorithms |
| Key implementation | final method template() { step1(); step2(); } |
| Pros | Reuse (Common code sits in superclass), Control (Superclass controls the flow) |
| Cons | Rigid (Must inherit from superclass), Liskov Substitution Principle risks |
Tips to Remember 🧠
- “The Recipe”: Think of the pasta recipe with variable ingredients.
- “Hooks”: Methods that are empty in the parent (
{}) but can be overridden are called “Hooks”. They let subclasses explicitly “hook into” the algorithm at specific points.
Advertisement
Moshiour Rahman
Software Architect & AI Engineer
Enterprise software architect with deep expertise in financial systems, distributed architecture, and AI-powered applications. Building large-scale systems at Fortune 500 companies. Specializing in LLM orchestration, multi-agent systems, and cloud-native solutions. I share battle-tested patterns from real enterprise projects.
Related Articles
The Strategy Design Pattern: Kill the If-Else Statements
Master the Strategy Pattern in Java. Learn how to replace complex if-else logic with interchangeable algorithms and follow the Open/Closed Principle.
JavaThe State Design Pattern: Machines with Personality
Master the State Pattern in Java. Learn how to let an object alter its behavior when its internal state changes, replacing massive switch statements.
JavaThe Visitor Design Pattern: Add Operations Without Modifying Classes
Master the Visitor Pattern in Java. Learn how to add new operations to object structures using double dispatch.
Comments
Comments are powered by GitHub Discussions.
Configure Giscus at giscus.app to enable comments.