design patterns · behavioral

Template Method

Defines the skeleton of an algorithm in a base class, deferring specific steps to subclasses.

easybehavioral0.5h
Ask GPTConfidence

Pattern

Overview

Intent

Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.

Real-World Analogy

A recipe template - preheat oven (fixed), add ingredients (you choose), bake for 30 min (fixed), cool (fixed). The template defines the structure; you customize the filling.

When multiple classes share the same algorithm structure but differ in specific steps, pull the common structure into a base class template method. Subclasses override only the varying steps.

The template method is declared final (or non-overridable) in the abstract base class. It calls abstract hook methods at appropriate points. Subclasses implement the hooks. The overall algorithm structure is fixed.

When to use

Data parsing pipelines, report generation, game loops, build processes, testing frameworks - any workflow with fixed overall structure but variable steps.

When not to

When you need runtime algorithm switching - use Strategy. When the varying steps are too different - the base class becomes incoherent.

Participants

AbstractClassConcreteClass

Key Insights

  • Template Method is compile-time flexibility via inheritance; Strategy is runtime flexibility via composition
  • Hook methods can have default implementations - subclasses may override but do not have to
  • The Hollywood Principle: the base class calls subclass methods, not the other way around
  • JUnit setUp/tearDown are Template Method hooks called by the test framework