State Pattern
Explore the State Pattern to understand how an object changes behavior based on its internal state. Learn to replace complex conditional logic with state-specific classes, making your designs more maintainable and extensible. This lesson demonstrates the pattern using an F-16 aircraft example, guiding you through state transitions and implementation in Java.
We'll cover the following...
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
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 ...