Bird
Raised Fist0
LLDsystem_design~7 mins

Strategy 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 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.

Practice

(1/5)
1. What is the main purpose of the Strategy pattern in system design?
easy
A. To restrict object creation to a single instance
B. To allow selecting an algorithm's behavior at runtime without changing the client code
C. To define a fixed sequence of steps for an algorithm
D. To create a single global instance of a class

Solution

  1. Step 1: Understand the Strategy pattern goal

    The Strategy pattern is designed to let you swap algorithms or behaviors dynamically without changing the client code.
  2. Step 2: Compare options with pattern purpose

    To allow selecting an algorithm's behavior at runtime without changing the client code correctly states this purpose. Options A and B describe Singleton pattern, and C describes Template Method pattern.
  3. Final Answer:

    To allow selecting an algorithm's behavior at runtime without changing the client code -> Option B
  4. Quick Check:

    Strategy pattern = runtime algorithm selection [OK]
Hint: Strategy pattern = choose behavior at runtime [OK]
Common Mistakes:
  • Confusing Strategy with Singleton pattern
  • Thinking Strategy fixes algorithm steps
  • Assuming Strategy creates single instances
2. Which of the following is the correct way to define a Strategy interface in a typical object-oriented language?
easy
A. class Strategy { void execute(); }
B. def Strategy(): pass
C. interface Strategy { void execute(); }
D. struct Strategy { void execute(); }

Solution

  1. Step 1: Identify the correct syntax for interface definition

    In many object-oriented languages like Java or C#, interface keyword is used to define a Strategy interface with method signatures.
  2. Step 2: Evaluate options

    interface Strategy { void execute(); } uses interface with method execute(), which is correct. class Strategy { void execute(); } defines a class, not an interface. def Strategy(): pass is Python syntax but incomplete. struct Strategy { void execute(); } uses struct which is not typical for interfaces.
  3. Final Answer:

    interface Strategy { void execute(); } -> Option C
  4. Quick Check:

    Strategy interface = interface with method [OK]
Hint: Strategy interface uses 'interface' keyword in OOP [OK]
Common Mistakes:
  • Using class instead of interface for Strategy
  • Confusing struct with interface
  • Using incomplete or wrong language syntax
3. Given the following code snippet using the Strategy pattern, what will be the output?
class Context:
    def __init__(self, strategy):
        self.strategy = strategy
    def execute(self):
        return self.strategy.do_action()

class StrategyA:
    def do_action(self):
        return 'Action A'

class StrategyB:
    def do_action(self):
        return 'Action B'

context = Context(StrategyB())
print(context.execute())
medium
A. Action B
B. Action A
C. Error: StrategyB has no method do_action
D. None

Solution

  1. Step 1: Trace object creation and method calls

    The Context is created with StrategyB() instance. Calling context.execute() calls StrategyB.do_action().
  2. Step 2: Check StrategyB.do_action() return value

    StrategyB.do_action() returns the string 'Action B', so print(context.execute()) outputs 'Action B'.
  3. Final Answer:

    Action B -> Option A
  4. Quick Check:

    Context with StrategyB = 'Action B' output [OK]
Hint: Context calls strategy's method, output matches chosen strategy [OK]
Common Mistakes:
  • Assuming default strategy is StrategyA
  • Thinking method do_action is missing
  • Confusing class and instance usage
4. Identify the error in the following Strategy pattern implementation:
class Context:
    def __init__(self, strategy):
        self.strategy = strategy
    def execute(self):
        return self.strategy.action()

class StrategyA:
    def do_action(self):
        return 'Action A'

context = Context(StrategyA())
print(context.execute())
medium
A. Context calls a method 'action' which does not exist in StrategyA
B. StrategyA class is missing the constructor
C. Context should not store strategy as an instance variable
D. No error, code runs correctly

Solution

  1. Step 1: Compare method names between Context and StrategyA

    Context calls self.strategy.action(), but StrategyA defines do_action(), not action().
  2. Step 2: Identify mismatch causing error

    This mismatch causes an AttributeError at runtime because action() is undefined in StrategyA.
  3. Final Answer:

    Context calls a method 'action' which does not exist in StrategyA -> Option A
  4. Quick Check:

    Method name mismatch = runtime error [OK]
Hint: Check method names match between context and strategy [OK]
Common Mistakes:
  • Ignoring method name mismatch
  • Assuming missing constructor causes error
  • Thinking strategy should not be stored in context
5. You are designing a payment system that supports multiple payment methods (credit card, PayPal, cryptocurrency). How would applying the Strategy pattern improve your system design?
hard
A. It requires hardcoding all payment methods inside a single class
B. It forces all payment methods to share the same implementation details
C. It prevents runtime selection of payment methods
D. It allows adding new payment methods without changing existing code by defining each as a separate strategy

Solution

  1. Step 1: Understand Strategy pattern benefits in payment methods

    Strategy pattern lets you define each payment method as a separate strategy class implementing a common interface.
  2. Step 2: Analyze how this affects system design

    This design allows adding new payment methods easily without modifying existing code, and lets the system select payment method at runtime.
  3. Final Answer:

    It allows adding new payment methods without changing existing code by defining each as a separate strategy -> Option D
  4. Quick Check:

    Strategy pattern = easy extension and runtime choice [OK]
Hint: Strategy pattern enables easy addition and runtime choice [OK]
Common Mistakes:
  • Thinking Strategy forces shared implementation
  • Believing all methods must be hardcoded together
  • Assuming runtime selection is not possible