Bird
0
0
LLDsystem_design~7 mins

Strategy pattern in LLD - System Design Guide

Choose your learning style9 modes available
Problem Statement
When a system uses many conditional statements to choose different behaviors, it becomes hard to maintain and extend. Adding new behaviors requires modifying existing code, increasing the risk of bugs and violating the open/closed principle.
Solution
The Strategy pattern solves this by defining a family of interchangeable algorithms or behaviors encapsulated in separate classes. The system selects and uses these behaviors at runtime without changing its own code, enabling easy extension and cleaner design.
Architecture
Context
Strategy A
Strategy B
Strategy C
Strategy C

This diagram shows a Context class that holds a reference to a Strategy interface. Different concrete Strategy classes implement this interface. The Context delegates behavior to the selected Strategy at runtime.

Trade-offs
✓ Pros
Enables adding new behaviors without changing existing code, supporting open/closed principle.
Reduces complex conditional logic by encapsulating algorithms in separate classes.
Improves code readability and maintainability by separating concerns.
✗ Cons
Increases the number of classes, which can complicate the codebase if overused.
Clients must be aware of different strategies and select them appropriately.
May introduce slight runtime overhead due to delegation.
Use when you have multiple related algorithms or behaviors that need to be interchangeable and when you want to avoid large conditional statements. Suitable for systems requiring runtime behavior changes.
Avoid when the number of behaviors is small and unlikely to change, as the added complexity of multiple classes may not be justified.
Real World Examples
Amazon
Uses Strategy pattern to select different payment methods dynamically during checkout without changing the core payment processing logic.
Uber
Applies Strategy pattern to switch between different pricing algorithms based on location, time, or demand.
Netflix
Uses Strategy pattern to select different video encoding strategies depending on device capabilities and network conditions.
Code Example
The before code uses if-else statements inside a single class to handle different payment methods, making it hard to add new methods. The after code defines a PaymentStrategy interface and separate classes for each payment method. The PaymentProcessor class delegates payment to the selected strategy, enabling easy extension and cleaner code.
LLD
### Before: Using conditionals to select behavior
class PaymentProcessor:
    def pay(self, method, amount):
        if method == 'credit_card':
            print(f"Processing credit card payment of {amount}")
        elif method == 'paypal':
            print(f"Processing PayPal payment of {amount}")
        else:
            print(f"Unknown payment method: {method}")

# Usage
processor = PaymentProcessor()
processor.pay('credit_card', 100)


### After: Using Strategy pattern
from abc import ABC, abstractmethod

class PaymentStrategy(ABC):
    @abstractmethod
    def pay(self, amount):
        pass

class CreditCardPayment(PaymentStrategy):
    def pay(self, amount):
        print(f"Processing credit card payment of {amount}")

class PayPalPayment(PaymentStrategy):
    def pay(self, amount):
        print(f"Processing PayPal payment of {amount}")

class PaymentProcessor:
    def __init__(self, strategy: PaymentStrategy):
        self.strategy = strategy

    def pay(self, amount):
        self.strategy.pay(amount)

# Usage
processor = PaymentProcessor(CreditCardPayment())
processor.pay(100)

processor.strategy = PayPalPayment()
processor.pay(200)
OutputSuccess
Alternatives
State pattern
State pattern changes behavior based on internal state transitions, while Strategy pattern changes behavior based on external selection of algorithms.
Use when: Choose State pattern when behavior depends on the object's state and transitions between states.
Template Method
Template Method defines a fixed algorithm structure with customizable steps, whereas Strategy pattern encapsulates entire algorithms separately.
Use when: Choose Template Method when you want to enforce an algorithm skeleton with some steps customizable.
Summary
Strategy pattern encapsulates interchangeable behaviors in separate classes to avoid complex conditionals.
It enables selecting algorithms at runtime without modifying existing code, supporting open/closed principle.
This pattern improves maintainability and extensibility by separating concerns and delegating behavior.