State Pattern

This lesson discusses how an object exhibits very different behavior and appears to be an instance of a different class when its internal state changes under the state pattern.

What is it ?

The state pattern will be reminiscent of automata class from your undergraduate degree as it involves state transitions for an object. The state pattern encapsulates the various states a machine can be in. The machine or the context, as it is called in pattern-speak, can have actions taken on it that propel it into different states. Without the use of the pattern, the code becomes inflexible and littered with if-else conditionals.

Formally, the pattern is defined as allowing an object to alter behavior when its internal state changes so that it appears to change its class.

Class Diagram

The class diagram consists of the following entities

  • Context
  • State
  • Concrete State Subclasses
widget

Example

Let's take the case of our F-16 class. An instance of the class can be in various states. Some possible states and transitions to other states are listed below:

Current State Possible Transitions to Other States
Parked Crash or Taxi
Taxi Airborne or Parked
Airborne Crash or Land
Land Taxi
Crash No transition out of this state

The state transitions are depicted in the picture below:

The verbs in red in the state diagram are actions that propel the aircraft into different states.

Let's see how we'll write the code in the absence ...