RecapDifficulty: Advanced1 min

Recap: State Pattern

One class per state, the context delegates, and one agreed place decides the next state.

State replaces a status field and its repeated checks with one class per state.

  • Intent. Let an object change its behaviour when its internal state changes, as if it changed its class.
  • Structure. The context holds the current state and passes each request to it; each concrete state handles requests for one state.
  • From a diagram. Each box is a class, and each arrow is a line in the class it leaves.
  • Who decides. Usually the state classes, sometimes the context, never the client, and always one of them for the whole design.
  • Against Strategy. The structure is the same; a strategy is chosen by the client, while states replace one another.
  • The trap. Transitions split between context and states, so a rule runs on an arrow the object never took.
  • When not. Two or three states with little behaviour, or transitions that are data.

← → move through sections and cards