JavaOmnibus
GoF Template Method
GoF pattern • Behavioral
GoFBehavioralJava example

Template Method solves a specific structural problem in the design.

Define the workflow skeleton and let subclasses fill in specific steps.

Pattern overview

GoF pattern

Define the workflow skeleton and let subclasses fill in specific steps.

Intent

Define the skeleton of an algorithm in a method, deferring some steps to subclasses.

Problem

The overall workflow is fixed, but certain steps must vary across implementations.

Solution

Keep the algorithm in the base class and override the variation points.

Fit and tradeoffs

FamilyGoF
CategoryBehavioral
Best used when
  • When multiple implementations share the same broad sequence.
  • When workflow consistency matters more than free-form customization.
Tradeoffs
  • Couples variation to inheritance.
  • Can be less flexible than composition-based approaches.

Java example

This example is intentionally compact so the pattern shape stays easy to see.

abstract class CsvImportJob {
    public final void run(List<String> rows) {
        validate(rows);
        transform(rows);
        persist(rows);
    }

    protected abstract void validate(List<String> rows);
    protected abstract void transform(List<String> rows);
    protected abstract void persist(List<String> rows);
}

Related pages

Keep exploring