Java 3 min read

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.

MR

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):

  1. Boil Water.
  2. Add [Generic Pasta].
  3. Cook for [X Minutes].
  4. Drain.
  5. 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

Template Method 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

FeatureDetails
CategoryBehavioral
Problem SolvedCode duplication in similar algorithms
Key implementationfinal method template() { step1(); step2(); }
ProsReuse (Common code sits in superclass), Control (Superclass controls the flow)
ConsRigid (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

MR

Moshiour Rahman

Software Architect & AI Engineer

Share:
MR

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

Comments

Comments are powered by GitHub Discussions.

Configure Giscus at giscus.app to enable comments.