About Us Contact Us Write for Us Advertise
Home > System Design > Low-Level Design > Template Method Pattern in Java (with Example)
System Design › Low-Level Design

Template Method Pattern in Java (with Example)

The Template Method pattern explained: define an algorithm's fixed skeleton in a base class and let subclasses fill in the varying steps. The Hollywood Principle, Template Method vs Strategy, Java code and UML.

Shiv Pandey
Shiv Pandey
Oct 24, 2026 | 62 views
Template Method Pattern in Java (with Example)

🟠 Design Patterns · Behavioral · Senior

The Template Method pattern defines the skeleton of an algorithm in a base class but lets subclasses fill in specific steps. Think of a recipe: the overall steps are fixed (prep → cook → serve), but what you cook varies. When several classes share the same overall flow yet differ in a few steps, Template Method removes the duplication while keeping each variation's unique bits.

In one line: Template Method puts the fixed steps of an algorithm in a base-class method (the "template") and defers the variable steps to subclasses via abstract methods — so the structure is shared and only the differences are overridden.

The problem

You process data files: CSV, JSON, XML. Each follows the same flow — open the file, parse it, validate, save to DB, close. Only the parse step differs. If each processor is a separate class with the whole flow copy-pasted, you've duplicated the open/validate/save/close logic everywhere; fix a bug in "save" and you must fix it in all of them.

The solution: fix the skeleton, vary the steps

🟠 Put the overall flow in a final template method in the base class; make the varying step abstract for subclasses to implement:

abstract class DataProcessor {
    // the TEMPLATE METHOD — fixed skeleton, final so it can't be overridden
    public final void process(String file) {
        open(file);
        Data d = parse(file);   // ← the step that varies
        validate(d);
        save(d);
        close();
    }
    protected abstract Data parse(String file);   // subclasses fill this in
    private void open(String f){ /* shared */ }
    private void validate(Data d){ /* shared */ }
    private void save(Data d){ /* shared */ }
    private void close(){ /* shared */ }
}
class CsvProcessor extends DataProcessor {
    protected Data parse(String f){ /* CSV-specific parsing */ return null; }
}
class JsonProcessor extends DataProcessor {
    protected Data parse(String f){ /* JSON-specific parsing */ return null; }
}
process(): open → parse* → validate → save → close * the only step subclasses change CsvProcessor.parse() JsonProcessor.parse()

The flow lives in one place; each subclass supplies only its unique parse(). Fix "save" once and every processor benefits. New format? New subclass overriding one method.

The Hollywood Principle

🟠 Template Method embodies "Don't call us, we'll call you" — the base class controls the flow and calls down into the subclass's steps, rather than the subclass driving. This inversion of control is the key idea, and naming it is a strong senior signal. (Optional "hook" methods — empty by default — let subclasses optionally tweak extra points in the flow.)

Template Method vs Strategy

🟠 Both let you vary part of a behaviour, but the mechanism differs: Template Method uses inheritance (subclass overrides steps of a fixed skeleton), while Strategy uses composition (swap a whole algorithm object at runtime). Template Method varies steps within one algorithm at compile time; Strategy swaps the entire algorithm at runtime. Mentioning that trade-off shows depth.

Where you meet it

Everywhere in frameworks: HttpServlet's service() calls your doGet()/doPost(); JUnit calls setUp() → your test → tearDown(); Spring's template classes (JdbcTemplate) run boilerplate and call your callback; Collections.sort calls your compareTo. Any framework that runs a fixed process and calls your code at defined points is using Template Method.

When to use it

Use it when several variants share the same overall algorithm but differ in a few steps, and you want to avoid duplicating the shared structure. If the variation is a whole interchangeable algorithm chosen at runtime, prefer Strategy; if there's no shared skeleton, this pattern doesn't apply.

The interview-ready summary

"Template Method puts an algorithm's fixed skeleton in a base-class method (usually final) and defers the varying steps to subclasses via abstract methods — so shared structure lives in one place and subclasses override only their differences. It follows the Hollywood Principle ('don't call us, we'll call you') — the base class drives and calls down into subclass steps. Unlike Strategy (composition, swap whole algorithm at runtime), it uses inheritance to vary steps. Real examples: HttpServlet, JUnit's setUp/tearDown, JdbcTemplate." That's it, with the Strategy contrast and Hollywood Principle."

What to read next

← Command pattern · Chain of Responsibility →

Related Articles

Factory Method Pattern in Java (with Example)
System Design › Low-Level Design

Factory Method Pattern in Java (with Example)

Chain of Responsibility Pattern in Java (Example)
System Design › Low-Level Design

Chain of Responsibility Pattern in Java (Example)

Command Pattern in Java (with Undo Example)
System Design › Low-Level Design

Command Pattern in Java (with Undo Example)

State Pattern in Java (with Example)
System Design › Low-Level Design

State Pattern in Java (with Example)