Skip to content

State DP - Lecture Notes

State Pattern

Problem Type

  1. Finite number of states
  2. Finite number of transitions between states
  3. Each State behaves differently
  4. Switching state is transparent

Typical Programmer Approach to Problem

  1. Large conditionals in if/else or switch blocks
  2. Conditional branches based on state of instance variables

Why this is BAD

  1. Difficult to maintain change to transition logic requires changing instance variables in many conditions and or methods
  2. As conditional states grow, so does the difficulty in maintianing.
    • Have to re-order conditionals.
    • Have to modify condition statements.
    • Have to mdoify multiple methods.
  3. It is not as easy to model conditional logic transitions in a State Diagram like the one below! Programmer_State_DP
  4. It is VERY difficult to predict every desired state (Conditional) during design

A Better Approch

  1. Create classes for all possible states of an object
  2. Encapsulate state behavior into the classes that implement a State Interface
    • You may have an intermediate *Abstract Class for common/shared method behavior (i.e. duplicate code)
    • States MAY have a back-ref to the Context Object
      • Allows for easy transitioning by using Context Object to set the Context’s State
      • Might need transition data from context.
  3. The original object, the context, now just composes* itself of a current state** object.
  4. The context changes state by delegating transitions to its current state object.
    • The current state object transitions the context by setting the context’s current state object.
    • In some situations the context may transition its own state

UML Structure

Note

The State Pattern has the same UML as Strategy, but: 1. The State Pattern’s State Classes are composed of other states (Strategy is not composed of other Strategies). 2. The Client often sets the context’s strategy in the Strategy Pattern, where States often set the context current state in the State Pattern.

When to Use State

  • Use the State pattern when you have an object that behaves differently depending on its current state, the number of states is enormous, and the state-specific code changes frequently.
  • Use the pattern when you have a class polluted with massive conditionals that alter how the class behaves according to the current values of the class’s fields.
  • Use State when you have a lot of duplicate code across similar states and transitions of a condition-based state machine.

Real World Use Scenarios

🔄 Media Player Controls

  • Problem: A media player needs different behavior depending on whether it’s playing, paused, or stopped.
  • State Pattern Role: Encapsulates state-specific behaviors for PlayingState, PausedState, StoppedState.

🎮 Game Character Behavior

  • Problem: A character changes behavior when transitioning between states like idle, walking, running, or attacking.
  • State Pattern Role: Each state encapsulates its own logic for movement and actions.

🏧 ATM Machine Operations

  • Problem: An ATM behaves differently when idle, card inserted, authenticated, or out of service.
  • State Pattern Role: Each state handles actions like insert card, enter PIN, and withdraw differently.

💬 Text Editor Mode Switching

  • Problem: A text editor with modes like insert, select, and command (e.g., like Vim).
  • State Pattern Role: Input handling is delegated to the current mode’s state.

🔐 User Account Status

  • Problem: A user account might be in states like active, suspended, or locked, affecting login and access behavior.
  • State Pattern Role: Each state encapsulates permission logic and responses.

🛒 Online Order Workflow

  • Problem: An online order transitions through states like placed, paid, shipped, and delivered.
  • State Pattern Role: Each order state controls what actions (cancel, refund, ship) are allowed.

🔁 Traffic Light System

  • Problem: A traffic light cycles through green, yellow, and red states with time-based transitions.
  • State Pattern Role: Each state knows what the next state is and how long it lasts.

🔄 Workflow Engine or Approval Process

  • Problem: A document moves through review, approval, rejection, and published states.
  • State Pattern Role: Each state defines valid transitions and behaviors (e.g., edit, approve, reject).

📱 Mobile App Screen Navigation

  • Problem: The app’s behavior depends on which screen or tab is active (Home, Profile, Settings).
  • State Pattern Role: The active screen’s state controls what actions are visible or enabled.

🕹️ Gumball Machine Simulation

  • Problem: A gumball machine has states like NoCoin, HasCoin, Sold, and SoldOut.
  • State Pattern Role: Actions like insertCoin, ejectCoin, turnCrank, and dispense behave differently depending on state.