Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 57 ยท Behavioral Patterns

Template Method

Learn the Template Method design pattern: define the skeleton of an algorithm in a base class, let subclasses fill in steps and hooks, and compare it with Strategy.

The Template Method pattern defines the skeleton of an algorithm in one method of a base class and leaves some of its steps to subclasses. The base class decides the order of the steps; the subclasses decide how some of those steps are done. Subclasses can change a step, but they cannot reshuffle the algorithm.

Cooking shows the idea well. Making a hot drink always goes: boil water, brew, pour into a cup, add extras. Tea steeps leaves and adds lemon; coffee drips through a filter and adds sugar. The recipe is the template; the drink fills in the blanks. Frameworks use this constantly: a test runner calls setUp, then your test, then tearDown, and you only write the middle.

A fixed recipe with open steps

Template method One method that fixes the order of the steps.
Abstract steps Subclasses must provide these.
Hooks Optional steps with a default that subclasses may override.

The base class calls the subclass, not the other way around.

1 / 2

The structure

The base class has a template method that calls other methods in a fixed order. Some are implemented in the base class, some are abstract, and some are hooks: methods with an empty or default body that a subclass may override.

classDiagram
    class DataPipeline {
        <<abstract>>
        +run()
        #read()*
        #parse(raw)*
        #validate(rows)
        #write(rows)*
    }
    class CsvPipeline
    class JsonPipeline
    DataPipeline <|-- CsvPipeline
    DataPipeline <|-- JsonPipeline

run() is the template method. read, parse and write are abstract steps; validate is a hook with a default.

This inverts the usual control flow. A subclass does not call the base class; the base class calls the subclass at the right moment. People call this the Hollywood Principle: "don't call us, we'll call you."

A data pipeline

Every import job does the same things: read raw data, parse it into rows, validate, then write. Reading and parsing depend on the format, so subclasses supply them. Validation has a sensible default of "keep everything" that a subclass can tighten. The base class also owns the parts that must never be skipped, like counting rows and reporting the result.

JS A pipeline skeleton with steps and hooks

Press Run (or Ctrl + Enter) to see the console output here.

No output.

run is the same for both formats. The JSON class keeps the default validate and afterRun, the CSV class overrides both. A subclass that forgets a required step fails with a clear message. In Java, C++ and C# you would declare those steps abstract or pure virtual, so the compiler catches the mistake instead.

In Java the skeleton is usually marked final so no subclass can replace it. The Java snippet below is read-only; it shows only the shape:

Java
abstract class Pipeline {
    public final int run(String source) {   // final: the order is fixed
        var rows = parse(read(source));
        var valid = validate(rows);
        write(valid);
        return valid.size();
    }
    protected abstract String read(String source);
    protected abstract List<Row> parse(String raw);
    protected List<Row> validate(List<Row> rows) { return rows; } // hook
    protected void write(List<Row> rows) { /* shared */ }
}

Hooks and the "before / after" shape

A hook is a step with a default, usually empty, implementation. Hooks let subclasses add behavior at defined points without having to override anything required. Three common kinds are:

  • Optional steps: validate above keeps everything unless overridden.
  • Notifications: afterRun(stats) tells the subclass the job finished.
  • Switches: a method such as shouldCompress() that returns true or false and lets a subclass turn a step on or off.

Keep the list of hooks short. Every hook is a promise you must keep stable, and too many make the base class hard to understand.

Template Method or Strategy?

Both patterns let you vary part of an algorithm. They do it differently.

Template Method Strategy
Mechanism Inheritance Composition
When you choose the variation At compile time, by picking a subclass At run time, by passing an object or function
Granularity Several steps of one algorithm The whole algorithm
Cost Subclass explosion, tight coupling to the base class An extra object to wire up

The same pipeline with composition simply passes the changeable steps in, so no subclass is needed and the behavior can change per call. In JavaScript or Python, passing functions is often the lighter option.

JS The same pipeline using composition

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The trade-off is control: a subclass-based template can protect the order of steps with final, and the base class can share internal state between steps naturally through this. A function-based version is easier to test and recombine.

When to use it

Use Template Method when several classes share the same algorithm with only a few differing steps, you want to centralize the shared parts, and the variation is naturally "kinds of X" rather than a choice made at run time. Typical examples are test fixtures, framework lifecycles (a request handler's before, handle and after), report generators that differ in format, and game AI turns.

Avoid it when the base class grows many hooks, when subclasses need to reorder steps, or when you want to combine several variations at once, because a class can only extend one parent. Another risk is the fragile base class problem: changing the template can break every subclass, because subclasses depend on exactly when their methods are called. Document the contract of each step.

Template Method often builds on a Factory Method, which is itself a template step that creates objects. For the run-time alternative see Strategy, and for the wider case against deep inheritance see DRY, KISS, YAGNI and Composition over Inheritance.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the template method itself do?

    The template method is the skeleton: it calls the steps in a fixed order, and subclasses fill in the steps that vary.
  2. 2. What is a hook in this pattern?

    Hooks give subclasses optional extension points. Abstract steps are mandatory; hooks are not.
  3. 3. What does the Hollywood Principle say?

    In Template Method the base class controls the flow and calls into subclass methods, which inverts the usual direction of calls.
  4. 4. Which statement correctly contrasts Template Method with Strategy?

    Template Method varies steps through subclasses, Strategy varies a whole algorithm through an object passed in, which can be swapped while the program runs.
  5. 5. Why is the 'fragile base class' problem a risk of Template Method?

    Subclasses are written against the base class's exact calling sequence. Changing that sequence can silently break every subclass.

Summary

  • Template Method puts the skeleton of an algorithm in a base class method and lets subclasses supply some steps.
  • Steps are abstract (required), concrete (shared) or hooks (optional with defaults).
  • The base class calls the subclass: the Hollywood Principle.
  • Mark the template method final (or document it) so the step order cannot be changed.
  • Strategy achieves a similar goal with composition and run-time choice; in dynamic languages, passing functions is often simpler.
  • Watch for too many hooks and for fragile base classes.

Next lesson: Iterator.