EMZETT.
Login

State pattern (state machine)

In short: The state pattern lets an object change its behaviour when its internal state changes. Behind it is the idea of a state machine.

In more detail: A machine has states (for example “open”, “paid”, “shipped”, “cancelled”) and allowed transitions. Instead of spreading many if checks over a status value, each behaviour is encapsulated in its own state.

In Depth

  • Order example: From “open” you can go to “paid” or “cancelled”, from “cancelled” no longer to “shipped”.
  • Advantages: Invalid transitions are impossible or easy to check, logic in one place.
  • Uses: traffic lights, game characters, network connections, order processes, parsers, UI flows.
  • Simple form: A table of allowed transitions (open → paid) is often enough.
  • State diagram: circles for states, arrows for transitions (UML).

See also: Strategy pattern, Command pattern