The State Pattern

The state pattern is useful when an object’s behavior is determined by its state given sufficient complexity. Events trigger the transition of a state to another. A formalized construct that manages the transitions is called a state machine.

To implement the pattern, we need to define:

  • A state entry and exit behaviors
  • Actions when a particular event causes a transition
  • Guard conditions enabling and disabling a transition
  • default actions when no transition is required for a particular event

For example, companies often used automated phone system to redirect and filter calls. We are given choices and depending on the choices, we are given specific answers or redirected to a person. This example is perfect for the state pattern. We can maintain a state object of the phone call and create rules that list the different options depending on the choices the caller made or redirect the call to another phone number.

Leave a comment

Design a site like this with WordPress.com
Get started