design patterns · behavioral

State

Allows an object to alter its behavior when its internal state changes, appearing to change its class.

mediumbehavioral1h
Ask GPTConfidence

Pattern

Overview

Intent

Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.

Real-World Analogy

A vending machine - behavior when you press a button differs based on state (idle, has coin, dispensing, out of stock).

When an object behaves very differently depending on its current state, putting all that logic in if/else chains becomes a maintenance nightmare. State moves each state's behavior into its own class.

Context holds a reference to the current State. When the client calls a method on Context, it delegates to the current State. State implementations handle the operation and may transition the Context to a new State.

When to use

Order processing workflows, vending machines, traffic lights, UI component states (enabled/disabled/loading), game character states, network connection states.

When not to

When behavior rarely changes with state. When there are only 2-3 states - a simple boolean or enum is clearer.

Participants

ContextStateConcreteState

Key Insights

  • State is similar to Strategy but State transitions between strategies automatically
  • Context delegates all state-dependent behavior to the current State object
  • State transitions can be managed by the Context or by State objects themselves
  • Finite State Machines in compilers, UI, and game engines commonly use this pattern