BEHAVIORAL PATTERNS / OBJECT DESIGN BRIEF

Template Method pattern

The Template Method pattern defines the skeleton of an algorithm in a base class method and lets subclasses fill in specific steps.

BeginnerPhase 06 / Topic 5 of 10ResponsibilitiesCollaborationsExtensibility
01

Overview

The Template Method pattern defines the skeleton of an algorithm in a base class method and lets subclasses fill in specific steps. The template method itself is final: it calls steps in a fixed order, some implemented in the base class, some abstract, and some optional 'hooks' with default behavior.

It removes duplicated workflow code across similar classes, such as data importers that all open, parse, validate, save, and close, or games that all initialize, play turns, and announce a winner. Its main drawback is inheritance coupling; Strategy is the composition-based alternative.

A recipe card with blanks

Every bread follows the same steps: mix, knead, rise, shape, bake. The recipe fixes the order; each type of bread fills in ingredients and baking time.

02

When to use it

  • Several classes share the same workflow but differ in some steps.
  • You want to enforce step order.
  • Framework extension points (lifecycle hooks).
03

Where it shows up in interviews

Shared workflows

Recognize it when: similar classes repeat the same sequence.

  • Design a data import pipeline (CSV, JSON, XML)
  • Design report generators
  • Design a board game framework
04

Where it is used in real software

java.util.AbstractList

Implements most List methods in terms of get() and size() that subclasses provide.

JUnit lifecycle

setUp/test/tearDown hooks follow a fixed template.

React class component lifecycle

componentDidMount and friends are hooks called by a fixed rendering algorithm.

05

Key terms

Template method
Final method defining the step order.
Primitive operation
Abstract step subclasses must implement.
Hook
Optional step with default behavior.
Hollywood principle
'Don't call us, we'll call you': the base calls subclass steps.
06

How it works, step by step

  1. 1
    Write the algorithm once

    In the base class, as a final method.

  2. 2
    Mark varying steps abstract

    parse(), transform().

  3. 3
    Provide hooks for optional steps

    beforeSave() { }.

  4. 4
    Implement subclasses

    Fill in the abstract steps only.

  5. 5
    Keep the template final

    Subclasses cannot reorder steps.

07

Data importers

importFile(): read -> parse -> validate -> save -> report

Step 1 / 5
StepBase classCsvImporterJsonImporter
readImplemented--
parseAbstractSplit lines by commasJSON.parse
validateImplemented (common rules)--
afterValidate (hook)Default: nothingTrim whitespace-
save and reportImplemented--

NOWStep: read | Base class: Implemented | CsvImporter: - | JsonImporter: -

Each importer is a few lines; the workflow and its order are defined once.

08

Implementation

public abstract class DataImporter {    // Template method: fixed order, cannot be overridden    public final ImportReport importFile(Path path) throws IOException {        String raw = Files.readString(path);        List<Record> records = parse(raw);        List<Record> valid = records.stream().filter(this::isValid).toList();        afterValidate(valid);        save(valid);        return new ImportReport(records.size(), valid.size());    }     protected abstract List<Record> parse(String raw);        // required step    protected void afterValidate(List<Record> records) {}     // hook     private boolean isValid(Record r) { return r.id() != null && !r.id().isBlank(); }    private void save(List<Record> records) { /* shared persistence */ }} public final class CsvImporter extends DataImporter {    @Override    protected List<Record> parse(String raw) {        return raw.lines().skip(1).map(line -> line.split(","))            .map(cols -> new Record(cols[0], cols[1])).toList();    }}
09

Complexity and performance

Code reuseWorkflow written once

Subclasses fill steps.

RuntimeVirtual calls per step

Negligible.

10

Trade-offs

Inheritance coupling

Subclasses depend on the base class; changes to the skeleton affect all of them.

Rigid order

Great for enforcing order; awkward when steps need to be combined differently.

11

Variants and related techniques

Strategy alternative

Pass step implementations as objects or functions to a workflow class.

Hooks with defaults

Optional customization points reduce required overrides.

12

Common mistakes

  • Template method not final.

    Fix: Subclasses might reorder or skip steps; make it final.

  • Too many abstract steps.

    Fix: Provide defaults as hooks; keep required steps minimal.

13

Interview questions

Template Method vs Strategy?

Template Method varies parts of an algorithm through inheritance, with the base class controlling order. Strategy replaces the whole algorithm through composition and can change at runtime.

What is a hook method?

An optional step in the template with a default (often empty) implementation that subclasses may override to customize behavior.

14

Practice problems

ProblemDifficultyWhat it trains
Report generator for PDF and HTMLEasySkeleton and steps.
Board game framework (chess, checkers)MediumTurn loop.