Browse Java Design Patterns & Enterprise Application Architecture

Implementing Template Method in Java

Implement Template Method in Java by fixing algorithm structure in a base type and deferring selected steps to subclasses.

On this page

Template Method: A pattern that fixes the skeleton of an algorithm in a base class while allowing subclasses to vary specific steps.

The classic Java shape looks like this:

 1public abstract class ReportExporter {
 2    public final void export(Report report) {
 3        validate(report);
 4        writeHeader(report);
 5        writeBody(report);
 6        finish(report);
 7    }
 8
 9    protected void validate(Report report) {}
10    protected abstract void writeHeader(Report report);
11    protected abstract void writeBody(Report report);
12    protected void finish(Report report) {}
13}

Subclasses customize the variable steps while the overall order stays fixed.

Why It Helps

Template Method works well when the algorithm order is a rule and variation should stay inside a limited set of hooks or abstract methods.

When It Is Overused

If subclasses only differ in one small behavior, Strategy or composition may be clearer than building a whole inheritance hierarchy.

Revised on Thursday, April 23, 2026