design patterns ·

State

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

medium1hgeneraljava
Ask GPTConfidence

Theory

Explanation

Intuition first, formal definition second. Skim the bullets if you already know this; read the prose if you don't.

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.

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