Skip to content
Low Level Design Mastery Logo
LowLevelDesign Mastery

Template Method Pattern

Define the skeleton of an algorithm - let subclasses fill in the details without changing the structure!

The Template Method Pattern is one of the most fundamental behavioral design patterns that defines the skeleton of an algorithm in a base class, letting subclasses override specific steps without changing the algorithm’s structure. Understanding the Template Method Pattern is essential for building flexible, maintainable software systems.

Imagine you’re making different types of beverages - tea and coffee. The process is similar: boil water, brew, pour, add condiments. But “brew” means steeping tea leaves for tea, and filtering coffee for coffee. The Template Method Pattern lets you define this common process once, with specific steps filled in by subclasses!

The Template Method Pattern defines the skeleton of an algorithm in a base class method, deferring some steps to subclasses. It lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.

What’s the Use of Template Method Pattern?

Section titled “What’s the Use of Template Method Pattern?”

The Template Method Pattern is useful when:

  1. You have a common algorithm structure - Same steps, different details
  2. You want to avoid code duplication - Common code in base class
  3. You need to control extension points - Subclasses can only customize certain steps
  4. You want to enforce algorithm structure - Subclasses can’t change the order
  5. You have invariant steps - Some steps must always happen

What Happens If We Don’t Use Template Method Pattern?

Section titled “What Happens If We Don’t Use Template Method Pattern?”

Without the Template Method Pattern, you might:

  • Duplicate code - Same algorithm structure in multiple places
  • Inconsistent implementations - Different classes implement differently
  • Hard to maintain - Changes needed in multiple places
  • No control over extensions - Subclasses can change everything
  • Violate DRY - Don’t Repeat Yourself principle violated

Let’s start with a super simple example that anyone can understand!

Diagram

Here’s how the template method works - same structure, different implementations:

sequenceDiagram
    participant Client
    participant Tea
    participant Coffee
    participant BaseClass as Beverage (Base)
    
    Client->>Tea: prepare_recipe()
    activate Tea
    
    Tea->>BaseClass: boil_water()
    BaseClass-->>Tea: Water boiled
    
    Tea->>Tea: brew() [steep tea]
    Note right of Tea: Subclass implementation
    
    Tea->>BaseClass: pour_in_cup()
    BaseClass-->>Tea: Poured
    
    Tea->>Tea: add_condiments() [add lemon]
    Note right of Tea: Subclass implementation
    
    Tea-->>Client: Tea ready!
    deactivate Tea
    
    Client->>Coffee: prepare_recipe()
    activate Coffee
    
    Coffee->>BaseClass: boil_water()
    BaseClass-->>Coffee: Water boiled
    
    Coffee->>Coffee: brew() [drip coffee]
    Note right of Coffee: Different implementation
    
    Coffee->>BaseClass: pour_in_cup()
    BaseClass-->>Coffee: Poured
    
    Coffee->>Coffee: add_condiments() [add milk]
    Note right of Coffee: Different implementation
    
    Coffee-->>Client: Coffee ready!
    deactivate Coffee

You’re building a beverage maker that can make tea and coffee. Without Template Method Pattern:

Problems:

  • Code duplication - Same steps copied everywhere
  • Maintenance nightmare - Change in multiple places
  • No structure enforcement - Easy to forget steps
  • Violates DRY principle
classDiagram
    class Beverage {
        <<abstract>>
        +prepare_recipe() void
        +boil_water() void
        #brew()* void
        +pour_in_cup() void
        #add_condiments()* void
    }
    class Tea {
        #brew() void
        #add_condiments() void
    }
    class Coffee {
        #brew() void
        #add_condiments() void
    }
    class HotChocolate {
        #brew() void
        #add_condiments() void
    }
    
    Beverage <|-- Tea : extends
    Beverage <|-- Coffee : extends
    Beverage <|-- HotChocolate : extends
    
    note for Beverage "Template method: prepare_recipe()\nConcrete: boil_water(), pour_in_cup()\nAbstract: brew(), add_condiments()"

Real-World Software Example: Data Mining Pipeline

Section titled “Real-World Software Example: Data Mining Pipeline”

Now let’s see a realistic software example - a data mining pipeline that processes data from different sources.

You’re building a data processing system that needs to handle CSV files, JSON APIs, and databases. The process is similar: open connection, extract data, transform, analyze, generate report, close connection. Without Template Method:

Problems:

  • Common steps duplicated across all miners
  • Changes need to be made in multiple places
  • No enforcement of the mining process
classDiagram
    class DataMiner {
        <<abstract>>
        +mine(source) void
        #open_source(source)* void
        #extract_data()* List
        +transform_data(data) List
        +analyze_data(data) Report
        +generate_report(analysis) void
        #close_source()* void
        +hook_before_analysis() void
    }
    class CSVDataMiner {
        #open_source(source) void
        #extract_data() List
        #close_source() void
    }
    class JSONAPIMiner {
        #open_source(source) void
        #extract_data() List
        #close_source() void
    }
    class DatabaseMiner {
        #open_source(source) void
        #extract_data() List
        #close_source() void
        +hook_before_analysis() void
    }
    
    DataMiner <|-- CSVDataMiner : extends
    DataMiner <|-- JSONAPIMiner : extends
    DataMiner <|-- DatabaseMiner : extends
    
    note for DataMiner "Template method: mine()\nAbstract: open, extract, close\nConcrete: transform, analyze, report\nHook: hook_before_analysis()"

Hooks are optional methods that can be overridden:

Hooks allow:

  • Optional customization without forcing implementation
  • Conditional execution of steps
  • Default behavior that can be changed

“Don’t call us, we’ll call you” - Base class calls subclass methods:

sequenceDiagram
    participant Client
    participant BaseClass
    participant SubClass
    
    Client->>BaseClass: templateMethod()
    BaseClass->>BaseClass: step1()
    BaseClass->>SubClass: abstractStep2()
    Note right of SubClass: Subclass method called by base
    SubClass-->>BaseClass: return
    BaseClass->>BaseClass: step3()
    BaseClass-->>Client: done

Use Template Method Pattern when:

Common algorithm structure - Same steps, different implementations
Code duplication - Same structure repeated in multiple classes
Control extension points - Only certain steps can be customized
Enforce invariant steps - Some steps must always happen
Hollywood Principle - Framework calls user code

Don’t use Template Method Pattern when:

Algorithms are completely different - No common structure
All steps need customization - Use Strategy instead
Inheritance isn’t appropriate - Use composition
Simple cases - Just a few steps, no duplication


Mistake 1: Making Template Method Overridable

Section titled “Mistake 1: Making Template Method Overridable”

Mistake 3: Not Using Hooks for Optional Steps

Section titled “Mistake 3: Not Using Hooks for Optional Steps”

  1. Code Reuse - Common code in base class
  2. Algorithm Structure - Can’t be changed by subclasses
  3. Single Point of Change - Fix bugs once
  4. Controlled Extension - Only specific steps customizable
  5. Inversion of Control - Hollywood Principle
  6. DRY Principle - Don’t Repeat Yourself

Template Method Pattern is a behavioral design pattern that defines the skeleton of an algorithm in a base class method, letting subclasses override specific steps without changing the algorithm’s structure.

  • Code reuse - Common steps in base class
  • Algorithm structure - Fixed, can’t be changed
  • Controlled extension - Only specific steps customizable
  • DRY principle - No duplication
  • Hollywood Principle - “Don’t call us, we’ll call you”
  1. Create abstract base class - With template method
  2. Define template method - The algorithm skeleton
  3. Add concrete methods - Common implementations
  4. Add abstract methods - Customization points
  5. Add hooks - Optional customization
  6. Create subclasses - Implement abstract methods
Abstract Class (Template Method)
├── template_method() → defines algorithm
├── concrete_step() → common implementation
├── abstract_step() → subclass implements
└── hook() → optional override
class Beverage(ABC):
def prepare_recipe(self): # Template method
self.boil_water() # Concrete
self.brew() # Abstract
self.pour_in_cup() # Concrete
self.add_condiments() # Abstract
def boil_water(self):
print("Boiling water")
@abstractmethod
def brew(self): pass
@abstractmethod
def add_condiments(self): pass

✅ Common algorithm structure
✅ Code duplication in algorithm
✅ Need to control extension points
✅ Invariant steps must happen
✅ Framework development

❌ Completely different algorithms
❌ All steps need customization
❌ Simple cases with no duplication

  • Template Method = Algorithm skeleton in base class
  • Abstract methods = Customization points
  • Concrete methods = Common implementation
  • Hooks = Optional customization
  • Hollywood Principle = Base calls subclass methods

What to say:

“Template Method Pattern is a behavioral design pattern that defines the skeleton of an algorithm in a base class method, letting subclasses override specific steps without changing the algorithm’s structure. It promotes code reuse and enforces a consistent algorithm structure.”

Why it matters:

  • Shows you understand the fundamental purpose
  • Demonstrates knowledge of inheritance-based patterns
  • Indicates you can explain concepts clearly

Must discuss:

Example to give:

“Template Method is like a form with blanks to fill in - the structure is fixed, you just provide specific content. Strategy is like choosing a completely different form. Template Method changes parts of an algorithm; Strategy changes the entire algorithm.”

Must explain:

  • “Don’t call us, we’ll call you”
  • Base class calls subclass methods (inversion of control)
  • Framework pattern - framework controls flow

Example to give:

“In Template Method, the base class controls when subclass methods are called - this is the Hollywood Principle. The subclass doesn’t call the base class to get things done; instead, the base class calls down to the subclass when it needs specific implementation.”

Benefits to mention:

  • Code reuse - Common code in base class
  • Consistent structure - Algorithm can’t be altered
  • Single point of change - Fix bugs once
  • Controlled extension - Limited customization points
  • DRY principle - No duplication

Trade-offs to acknowledge:

  • Inheritance limitation - Java single inheritance
  • Harder to understand - Need to trace through hierarchy
  • Tight coupling - Subclasses tied to base class structure
  • Fragile base class - Changes to base affect all

Q: “When would you use Template Method over Strategy?”

A:

“I’d use Template Method when I have a fixed algorithm structure with specific steps that vary. For example, a data processing pipeline where opening, transforming, and closing are always the same, but extracting data varies by source. I’d use Strategy when I want to swap the entire algorithm, like different sorting algorithms that have completely different approaches.”

Q: “What are hooks in Template Method?”

A:

“Hooks are methods with default (usually empty) implementations that subclasses CAN override but don’t have to. Unlike abstract methods which MUST be overridden, hooks are optional. They provide additional customization points without forcing implementation. For example, a hook before saving that’s empty by default but can add validation.”

Q: “How does Template Method relate to SOLID principles?”

A:

“Template Method supports Open/Closed Principle - the algorithm structure is closed for modification but open for extension via abstract methods. It can violate Single Responsibility if the base class does too much. It demonstrates Dependency Inversion at the method level - the high-level algorithm depends on abstractions (abstract methods), not concrete implementations.”

Before your interview, make sure you can:

  • Define Template Method Pattern clearly
  • Explain the difference from Strategy Pattern
  • Describe the Hollywood Principle
  • Implement Template Method from scratch
  • List benefits and trade-offs
  • Explain hooks vs abstract methods
  • Give 2-3 real-world examples
  • Discuss when NOT to use it
  • Connect to SOLID principles

Remember: Template Method Pattern is about defining the skeleton of an algorithm - let subclasses fill in the details without changing the structure! 📋