Bird
0
0
LLDsystem_design~7 mins

Template Method pattern in LLD - System Design Guide

Choose your learning style9 modes available
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.