Bird
Raised Fist0
LLDsystem_design~7 mins

State 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 an object changes its behavior based on its internal state, using many conditional statements (if-else or switch) makes the code complex and hard to maintain. This leads to bugs and difficulty in adding new states or behaviors.
Solution
The State pattern solves this by encapsulating each state into separate classes with their own behavior. The main object delegates state-specific behavior to the current state object, allowing easy state transitions and cleaner code without large conditional blocks.
Architecture
┌───────────────┐       ┌───────────────┐       ┌───────────────┐
│   Context     │──────▶│   State A     │       │   State B     │
│ (has current  │       │ (implements   │       │ (implements   │
│  state)       │       │  behavior)    │       │  behavior)    │
└───────────────┘       └───────────────┘       └───────────────┘
        │                      ▲                       ▲
        │                      │                       │
        └──────────────────────┴───────────────────────┘
                 State interface with common methods

This diagram shows the Context holding a reference to a State interface. Concrete State classes implement this interface and define behavior for each state. The Context delegates requests to the current State object.

Trade-offs
✓ Pros
Improves code organization by separating state-specific behavior into classes.
Makes adding new states easier without modifying existing code.
Reduces complex conditional logic and improves readability.
Supports dynamic state transitions at runtime.
✗ Cons
Increases the number of classes, which can add complexity for small systems.
Requires careful design to avoid state explosion if many states exist.
May introduce overhead due to delegation and object creation.
Use when an object has multiple states with distinct behaviors and state transitions are frequent or complex. Suitable for systems where maintainability and extensibility of state logic are important.
Avoid when the number of states is very small and unlikely to change, or when state behavior is simple enough to handle with straightforward conditional statements.
Real World Examples
Amazon
Amazon uses the State pattern in order processing to manage order states like Pending, Shipped, Delivered, and Cancelled, each with specific behaviors and transitions.
Netflix
Netflix applies the State pattern in video playback controls, managing states such as Playing, Paused, and Buffering with distinct user interactions.
Uber
Uber uses the State pattern to handle ride statuses like Requested, Accepted, In Progress, and Completed, enabling clear state transitions and behavior.
Code Example
The before code uses if-else to switch behavior based on a string state, which becomes hard to maintain as states grow. The after code defines a State interface and concrete State classes. The Context delegates behavior to the current State object, which changes the Context's state dynamically. This improves extensibility and readability.
LLD
### Before: Using conditionals
class Context:
    def __init__(self):
        self.state = 'A'

    def request(self):
        if self.state == 'A':
            print('Behavior for state A')
            self.state = 'B'
        elif self.state == 'B':
            print('Behavior for state B')
            self.state = 'A'

context = Context()
context.request()  # Behavior for state A
context.request()  # Behavior for state B


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

class State(ABC):
    @abstractmethod
    def handle(self, context):
        pass

class StateA(State):
    def handle(self, context):
        print('Behavior for state A')
        context.state = StateB()

class StateB(State):
    def handle(self, context):
        print('Behavior for state B')
        context.state = StateA()

class Context:
    def __init__(self):
        self.state = StateA()

    def request(self):
        self.state.handle(self)

context = Context()
context.request()  # Behavior for state A
context.request()  # Behavior for state B
OutputSuccess
Alternatives
Strategy pattern
Strategy encapsulates interchangeable algorithms or behaviors but does not manage state transitions internally.
Use when: Choose Strategy when you need to switch algorithms dynamically without managing complex state transitions.
Simple conditional logic
Uses if-else or switch statements to handle states inline without separate classes.
Use when: Use simple conditionals when the number of states is very small and unlikely to grow.
Summary
The State pattern helps manage complex state-dependent behavior by encapsulating states into separate classes.
It eliminates large conditional statements and makes adding new states easier and safer.
This pattern improves code maintainability and supports dynamic state transitions at runtime.

Practice

(1/5)
1. What is the main purpose of the State pattern in system design?
easy
A. To provide a global point of access to a resource
B. To create multiple instances of a class efficiently
C. To allow an object to change its behavior when its internal state changes
D. To separate the construction of a complex object from its representation

Solution

  1. Step 1: Understand the role of the State pattern

    The State pattern helps an object change its behavior based on its internal state without changing its class.
  2. Step 2: Compare with other design patterns

    Other options describe Singleton (A), Prototype (B), and Builder (C) patterns, which are unrelated to state behavior changes.
  3. Final Answer:

    To allow an object to change its behavior when its internal state changes -> Option C
  4. Quick Check:

    State pattern = behavior change by internal state [OK]
Hint: State pattern changes behavior with state, not object creation [OK]
Common Mistakes:
  • Confusing State pattern with Singleton or Builder patterns
  • Thinking it manages object creation instead of behavior
  • Assuming it provides global access to resources
2. Which of the following is the correct way to define a state interface in a typical State pattern implementation?
easy
A. interface State { void handle(); }
B. class State { void handle() {} }
C. enum State { START, STOP }
D. struct State { int status; }

Solution

  1. Step 1: Identify the correct interface syntax

    The State pattern requires a State interface with a method like handle() to define behavior.
  2. Step 2: Eliminate incorrect options

    class State { void handle() {} } is a class, not an interface; C is an enum, not behavior; D is a struct without behavior.
  3. Final Answer:

    interface State { void handle(); } -> Option A
  4. Quick Check:

    State interface defines behavior method [OK]
Hint: State pattern needs interface with behavior method [OK]
Common Mistakes:
  • Using enum or struct instead of interface/class for behavior
  • Defining empty methods without interface
  • Confusing class and interface roles
3. Consider this simplified code snippet using the State pattern:
class Context {
  State state;
  void request() { state.handle(this); }
  void setState(State s) { state = s; }
}

class State {
  void handle(Context c) { c.setState(new StateB()); }
}

class StateB extends State {
  void handle(Context c) { c.setState(new State()); }
}

Context ctx = new Context();
ctx.setState(new State());
ctx.request();
ctx.request();
What is the final state of ctx after these two requests?
medium
A. An instance of State
B. An instance of StateB
C. Null (no state)
D. An error occurs

Solution

  1. Step 1: Trace first request()

    Initially, ctx.state = State instance. Calling request() calls State.handle(ctx), which sets state to new StateB.
  2. Step 2: Trace second request()

    Now ctx.state = StateB instance. Calling request() calls StateB.handle(ctx), which sets state back to new State.
  3. Final Answer:

    An instance of State -> Option A
  4. Quick Check:

    State and StateB toggle on requests [OK]
Hint: State and StateB toggle on each request call [OK]
Common Mistakes:
  • Assuming state stays the same after first request
  • Confusing which handle method is called
  • Ignoring state changes inside handle methods
4. In the following State pattern code, what is the main issue causing incorrect behavior?
interface State {
  void handle(Context c);
}

class Context {
  State state;
  void request() {
    state.handle(this);
  }
}

class ConcreteStateA implements State {
  void handle(Context c) {
    // Missing state transition
    System.out.println("State A handling");
  }
}

Context ctx = new Context();
ctx.state = new ConcreteStateA();
ctx.request();
ctx.request();
medium
A. State interface method signature is incorrect
B. Context's state is never updated inside handle, so state never changes
C. Context does not initialize state before request
D. ConcreteStateA does not implement handle method

Solution

  1. Step 1: Analyze state transitions in handle()

    ConcreteStateA.handle() prints a message but does not update Context's state, so no state change occurs.
  2. Step 2: Check other options

    State interface method is correct; Context initializes state before request; ConcreteStateA implements handle properly.
  3. Final Answer:

    Context's state is never updated inside handle, so state never changes -> Option B
  4. Quick Check:

    State transition missing inside handle() [OK]
Hint: State must update Context's state inside handle() [OK]
Common Mistakes:
  • Forgetting to update state inside handle method
  • Assuming printing is enough for state change
  • Ignoring initialization of state before request
5. You are designing a traffic light system using the State pattern. The traffic light cycles through Green, Yellow, and Red states. Which design choice best applies the State pattern to handle state transitions and behavior?
hard
A. Use a global variable to track color and update it externally without encapsulating behavior
B. Use a single class with a variable holding the current color and switch behavior using if-else statements
C. Implement the traffic light as a simple timer without state classes
D. Create separate state classes for Green, Yellow, and Red, each implementing a next() method to switch to the next state

Solution

  1. Step 1: Understand State pattern application

    The pattern suggests encapsulating each state in its own class with behavior and transitions.
  2. Step 2: Evaluate options for scalability and clarity

    Create separate state classes for Green, Yellow, and Red, each implementing a next() method to switch to the next state cleanly separates states and their transitions. Options B, C, and D mix logic or lack encapsulation, reducing maintainability.
  3. Final Answer:

    Create separate state classes for Green, Yellow, and Red, each implementing a next() method to switch to the next state -> Option D
  4. Quick Check:

    Separate classes with transitions = State pattern [OK]
Hint: Separate states as classes with next() method for transitions [OK]
Common Mistakes:
  • Using if-else instead of separate state classes
  • Not encapsulating state behavior inside classes
  • Relying on external variables without behavior