Behavioral Hook Method

Template Method

Template Method fixes the overall shape of an algorithm in a base class while leaving individual steps for subclasses to fill in, so the sequence of operations never changes even though its details do.

Complexity
Popularity

Problem

Imagine you're building a reporting tool that generates documents in different formats: HTML and Markdown. Both formats follow the same overall structure - a title header, a list of content rows, and a footer - but the exact markup for each step differs.

You could copy the entire algorithm into each report class. But then changing the overall flow (say, adding a timestamp section) requires modifying every class individually.

Alternatively, you could pack all the logic into one class and use conditionals to choose the output format - but that violates the Open/Closed Principle every time a new format is added.

Solution

The Template Method pattern suggests breaking the algorithm into steps, turning each step into a method, and putting a series of calls to those methods inside a single template method in the abstract class.

The steps may either be `abstract` (forcing subclasses to provide an implementation) or have a default implementation that subclasses can optionally override (hooks).

Subclasses can override specific steps without touching the template method itself. This guarantees that the overall algorithm structure stays the same while individual steps remain customizable.

When to Use

  • Reach for Template Method when subclasses should be free to customize a few specific steps of an algorithm, but must not be able to change its overall sequence.
  • It also fits when you notice several classes implementing almost the same algorithm with small variations, which today forces you to update every copy whenever the shared logic changes.

Real-World Examples

  • **Data parsers** - a document parser follows the same steps (open, parse, close) for CSV, JSON, and XML files, but each format requires different parsing logic.
  • **Web frameworks** - request handling pipelines (authenticate, authorize, handle, respond) define a skeleton that controllers override with specific handler logic.
  • **Game AI** - a turn-based AI defines a fixed turn structure (collect resources, build, attack) while different difficulty levels override each step with varying strategies.