Cover image for Design Pattern: The State Pattern

Design Pattern: The State Pattern

danlee0528 profile image Daniel Lee ・1 min read

The State Pattern allows an object to alter its behaviour when its internal state changes. The object will appear to change its class. It lets the client specify the strategy object that the context is composed with (as a flexible alternative to subclassing).

The state interface ("TCP state" in the diagram) defines a common interface for all concrete states (TCP Established/Listen/Closed).

The State and Strategy Patterns have the same class diagram, but they differ in intent!

  • The State Pattern as an alternative to putting lots of conditionals in your context; By encapsulating the behaviours within state objects, you can simply change the state object in context to change its behaviours.
  • The Strategy Pattern typically configures context classes with a behaviour or algorithm, and allows a context to change its behaviour as the state of the context changes. It will typically result in a greater number of classes in your design.

Posted on by:

danlee0528 profile

Daniel Lee


I love interactive & visual technology and playing with data.


Editor guide