skip to content

Template Method Pattern - Shared Workflow, Variable Steps

Updated: at 12:00 AM

1. The Problem

Problem: Shared Workflow, Variable Steps

Many systems follow a fixed overall process, but certain steps inside that process can vary. Examples:

Developers often solve this with:

def process():
    step1()

    if mode == "A":
        step2A()
    elif mode == "B":
        step2B()

    step3()

This leads to:

We need a solution where:

2. Template Method Pattern: Fix the Algorithm Structure, Vary the Steps

Template Method solves this by defining a fixed algorithm skeleton in a base class and letting subclasses customize specific parts.

Core idea:

Two roles exist:

Benefits:

Use Template Method when:

3. Implementation: Template Method in Python

Abstract Template

from abc import ABC, abstractmethod

class DataProcessor(ABC):
    def process(self, data):
        self.read(data)
        cleaned = self.clean(data)
        transformed = self.transform(cleaned)
        self.save(transformed)

    def read(self, data):
        print(f"Reading data: {data}")

    @abstractmethod
    def clean(self, data):
        pass

    @abstractmethod
    def transform(self, data):
        pass

    def save(self, data):
        print(f"Saving processed data: {data}")

Key points:

Concrete Implementations

class CSVProcessor(DataProcessor):
    def clean(self, data):
        return data.strip()

    def transform(self, data):
        return data.upper()
class JSONProcessor(DataProcessor):
    def clean(self, data):
        return data.replace(" ", "")

    def transform(self, data):
        return f"JSON({data})"

Usage

processor = CSVProcessor()
processor.process(" sample csv data ")

processor = JSONProcessor()
processor.process(" sample json data ")

No conditionals. No branching. Workflow is guaranteed. Behavior is extensible.

4. When to Use Template Method (and When Not To)

Strong Signals You Need Template Method

Not a Good Fit When

5. Common Pitfalls

Good rule: Template Method = fixed algorithm + controlled customization

6. Strategy vs Template Method (Mental Model)

Both solve “variation in behavior,” but in different ways:

Strategy PatternTemplate Method Pattern
Behavior chosen at runtimeBehavior chosen by subclass
Uses compositionUses inheritance
No fixed workflow enforcedFixed workflow enforced
Caller decides behaviorBase class decides process

If the question is: “I want interchangeable behaviors.” → Strategy

If the question is: “I want guaranteed workflow with customizable steps.” → Template Method