Bird
Raised Fist0
LLDsystem_design~7 mins

Template Method pattern in LLD - System Design Guide

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Problem Statement
When multiple classes share a similar algorithm structure but differ in some steps, duplicating the entire algorithm in each class leads to code repetition and maintenance challenges. Changes to the common parts require updates in many places, increasing the risk of bugs and inconsistencies.
Solution
The Template Method pattern defines the skeleton of an algorithm in a base class method, leaving some steps to be implemented by subclasses. This way, the common structure is centralized, and subclasses only override the variable parts, promoting code reuse and easier maintenance.
Architecture
AbstractClass
┌─────────────────┐

This diagram shows the base class defining the template method that calls steps, some of which are implemented by the subclass.

Trade-offs
✓ Pros
Centralizes common algorithm structure, reducing code duplication.
Allows subclasses to customize specific steps without changing the overall algorithm.
Improves code maintainability and readability by separating invariant and variant parts.
✗ Cons
Can lead to a rigid class hierarchy that is hard to change later.
Subclasses must follow the algorithm structure strictly, limiting flexibility.
Overuse may cause many small subclasses differing only in minor steps.
Use when multiple classes share the same overall algorithm but differ in some steps, especially if the algorithm is stable and unlikely to change frequently.
Avoid when the algorithm structure is highly dynamic or when subclassing is not feasible due to language constraints or design preferences.
Real World Examples
Netflix
Netflix uses the Template Method pattern in their video encoding pipeline where the overall process is fixed but encoding parameters vary by device type.
Amazon
Amazon applies this pattern in order processing where the sequence of steps is fixed but payment and shipping methods differ.
LinkedIn
LinkedIn uses Template Method in their notification system where message formatting varies but delivery steps remain consistent.
Code Example
The before code duplicates the generate method in each report class, repeating the algorithm steps. The after code moves the generate method to an abstract base class, defining the algorithm skeleton. Subclasses override only the variable steps, reducing duplication and improving maintainability.
LLD
### Before (without Template Method pattern):
class ReportA:
    def generate(self):
        self.load_data()
        self.process_data()
        self.format_report()
        self.save_report()

    def load_data(self):
        print("Loading data for Report A")

    def process_data(self):
        print("Processing data for Report A")

    def format_report(self):
        print("Formatting report A")

    def save_report(self):
        print("Saving report A")

class ReportB:
    def generate(self):
        self.load_data()
        self.process_data()
        self.format_report()
        self.save_report()

    def load_data(self):
        print("Loading data for Report B")

    def process_data(self):
        print("Processing data for Report B")

    def format_report(self):
        print("Formatting report B")

    def save_report(self):
        print("Saving report B")

### After (with Template Method pattern):
from abc import ABC, abstractmethod

class Report(ABC):
    def generate(self):
        self.load_data()
        self.process_data()
        self.format_report()
        self.save_report()

    @abstractmethod
    def load_data(self):
        pass

    @abstractmethod
    def process_data(self):
        pass

    @abstractmethod
    def format_report(self):
        pass

    def save_report(self):
        print("Saving report")

class ReportA(Report):
    def load_data(self):
        print("Loading data for Report A")

    def process_data(self):
        print("Processing data for Report A")

    def format_report(self):
        print("Formatting report A")

class ReportB(Report):
    def load_data(self):
        print("Loading data for Report B")

    def process_data(self):
        print("Processing data for Report B")

    def format_report(self):
        print("Formatting report B")
OutputSuccess
Alternatives
Strategy pattern
Strategy encapsulates interchangeable algorithms in separate classes and selects them at runtime, while Template Method fixes the algorithm structure in a base class and varies steps via subclassing.
Use when: Choose Strategy when you need to switch algorithms dynamically at runtime without subclassing.
Hook methods
Hook methods are optional steps in Template Method that subclasses may override, providing more flexibility within the fixed algorithm.
Use when: Choose Hook methods when you want to allow optional customization points without forcing subclasses to override all steps.
Summary
Template Method pattern centralizes the fixed algorithm structure in a base class.
It lets subclasses override specific steps without changing the overall process.
This reduces code duplication and improves maintainability in similar algorithms.

Practice

(1/5)
1. What is the main purpose of the Template Method pattern in system design?
easy
A. To replace all methods with completely new implementations
B. To define a fixed sequence of steps with some customizable parts
C. To allow direct modification of the entire process by subclasses
D. To create multiple unrelated classes with no shared behavior

Solution

  1. Step 1: Understand the Template Method pattern goal

    The pattern fixes the overall process flow but allows subclasses to customize certain steps.
  2. Step 2: Analyze each option

    To define a fixed sequence of steps with some customizable parts correctly describes this fixed sequence with customizable parts. Options A, B, and C do not match the pattern's intent.
  3. Final Answer:

    To define a fixed sequence of steps with some customizable parts -> Option B
  4. Quick Check:

    Template Method = fixed process + flexible steps [OK]
Hint: Remember: fixed order, flexible details [OK]
Common Mistakes:
  • Thinking subclasses rewrite the whole process
  • Confusing Template Method with Strategy pattern
  • Believing the pattern removes all common code
  • Assuming no steps are customizable
2. Which of the following is the correct way to declare a template method in a class?
easy
A. Override all methods in subclasses without calling base methods
B. Define multiple unrelated methods without calling each other
C. Define a method that calls other methods in a fixed order
D. Use a method that randomly calls other methods

Solution

  1. Step 1: Identify the structure of a template method

    A template method is a method that defines the sequence of steps by calling other methods in order.
  2. Step 2: Evaluate each option

    Define a method that calls other methods in a fixed order matches this definition. Options B, C, and D do not follow the fixed sequence concept.
  3. Final Answer:

    Define a method that calls other methods in a fixed order -> Option C
  4. Quick Check:

    Template method = fixed calls order [OK]
Hint: Template method calls steps in order [OK]
Common Mistakes:
  • Not calling methods in a fixed sequence
  • Overriding template method instead of steps
  • Ignoring the fixed process structure
  • Using random or unordered calls
3. Consider this simplified template method code in Python:
class Game:
    def play(self):
        self.start()
        self.play_turn()
        self.end()

    def start(self):
        print('Game started')

    def play_turn(self):
        print('Playing turn')

    def end(self):
        print('Game ended')

class Chess(Game):
    def play_turn(self):
        print('Chess turn played')

chess = Chess()
chess.play()

What will be the output when chess.play() is called?
medium
A. Game ended Chess turn played Game started
B. Chess turn played Game started Game ended
C. Game started Playing turn Game ended
D. Game started Chess turn played Game ended

Solution

  1. Step 1: Trace the play() method calls

    The play() method calls start(), play_turn(), and end() in order.
  2. Step 2: Identify overridden methods

    Chess overrides play_turn(), so Chess's version prints 'Chess turn played'. start() and end() use base class prints.
  3. Final Answer:

    Game started Chess turn played Game ended -> Option D
  4. Quick Check:

    Template calls base start/end + overridden play_turn [OK]
Hint: Overridden steps print their own messages [OK]
Common Mistakes:
  • Ignoring method overriding
  • Assuming base play_turn() runs
  • Mixing order of prints
  • Thinking play() is overridden
4. In the following code, what is the main problem that breaks the Template Method pattern?
class Report:
    def generate(self):
        self.load_data()
        self.process_data()
        self.save_report()

    def load_data(self):
        print('Loading data')

    def process_data(self):
        print('Processing data')

    def save_report(self):
        print('Saving report')

class CustomReport(Report):
    def generate(self):
        print('Custom generate start')
        self.load_data()
        self.process_data()
        self.save_report()
        print('Custom generate end')
medium
A. The subclass overrides the template method instead of steps
B. The base class does not define any methods
C. The subclass does not call any base methods
D. The base class methods are private

Solution

  1. Step 1: Identify the template method and overrides

    The base class defines generate() as the template method. The subclass overrides generate() itself.
  2. Step 2: Understand Template Method pattern rules

    In this pattern, subclasses should override steps, not the template method, to keep the fixed process intact.
  3. Final Answer:

    The subclass overrides the template method instead of steps -> Option A
  4. Quick Check:

    Template method must not be overridden [OK]
Hint: Override steps, not the template method [OK]
Common Mistakes:
  • Overriding the whole template method
  • Ignoring base class method definitions
  • Assuming private methods cause issues
  • Thinking subclass must call base generate() explicitly
5. You are designing a document processing system where each document type requires a specific sequence of steps: open, parse, validate, save, and close. You want to ensure the sequence is fixed but allow each document type to customize parsing and validation. How should you apply the Template Method pattern here?
hard
A. Create a base class with a template method calling open, parse, validate, save, close; subclasses override parse and validate
B. Let each subclass implement its own full process without a base class
C. Use separate unrelated classes for each step without a fixed sequence
D. Make all steps abstract and force subclasses to implement the entire process

Solution

  1. Step 1: Identify fixed and customizable parts

    The sequence (open, parse, validate, save, close) is fixed; parse and validate vary by document type.
  2. Step 2: Apply Template Method pattern correctly

    Create a base class with a template method that calls all steps in order. Subclasses override parse and validate to customize behavior.
  3. Final Answer:

    Create a base class with a template method calling open, parse, validate, save, close; subclasses override parse and validate -> Option A
  4. Quick Check:

    Fixed sequence + customizable steps = Template Method [OK]
Hint: Fix sequence in base; override variable steps in subclasses [OK]
Common Mistakes:
  • Not fixing the sequence in one place
  • Forcing subclasses to rewrite entire process
  • Ignoring the need for a template method
  • Separating steps without order control