Catalog / Behavioral Patterns / Template Method Pattern
BEHAVIORAL

Template Method Pattern

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

Intent & Objective

Let subclasses redefine certain steps of an algorithm without changing the algorithm’s structure, preserving the overall workflow invariant.

👥 Real-World Human Analogies & Social Roles
4 Intuitive Scenarios
Morning Routine Daily Human Life

"Everyone follows the general sequence (wake up, brush teeth, eat breakfast), but details vary (coffee vs tea, gym vs reading)."

Job Interview Format Hiring Process

"Structure is invariant (intro, technical questions, candidate Q&A, closing), but specific questions change by candidate role."

Cooking Pasta Cooking Recipe

"Invariant skeleton (boil water, cook pasta, drain), while the sauce step varies (marinara vs alfredo)."

Wind-Down Night Routine Developer Daily Life

"Fixed sequence (dinner, relax, sleep) with personal variations before bed."

The Problem

Duplicated workflow algorithms across classes where 80% of the workflow steps are identical and only 20% vary.

The Solution

Break down an algorithm into a series of steps, turn these steps into methods, and put a series of calls to these methods inside a single "template method" in the base class. Concrete subclasses override only the customizable hook methods.

Key Participants & Architectural Roles

Abstract Class
Declares template method defining algorithm skeleton and abstract hook steps
Concrete Classes
Overrides hook steps to customize specific algorithmic details

Code Samples (Traditional OOP vs Functional Programming)

Available in C++, Python, and Java

Paradigm Contrast: Traditional OOP vs Functional / Data-Oriented

In OOP, Template Method uses inheritance and abstract methods. In Functional Programming, Template Method is simply a higher-order function receiving callback functions for the customizable steps.

Advantages

  • ✓ Eliminates duplicate code by pulling the invariant algorithm into a superclass
  • ✓ Lets clients override only certain parts of a large algorithm, making them less affected by changes to other parts

Trade-offs

  • ✗ Subclasses can be limited by the rigid skeleton provided by the template method
  • ✗ Can violate Liskov Substitution Principle if a subclass suppresses a fundamental step

When to Apply

  • → When you want to let clients extend only particular steps of an algorithm, but not the whole algorithm or its structure
  • → When you have several classes that contain almost identical algorithms with only minor differences

When to Avoid

  • ! When the entire algorithm structure varies between variants