What is the State Pattern?
- Allow to sub-divide the behavior of an object depending on its current state.
- Classified as a behavior pattern.
- Also known as Objects for States.
When do you use the State Pattern?
Suppose that you are playing War Craft. Your units will behave according to your commands. For example, if the "Attack" command is given to your units, the state of the units will be changed to "Attack State" and they will attack the enemies around them. If you set them to hold their position, their state will be changed to "Hold Position" and your units will stop attacking and stand around. These behaviors such as "attack" behavior and "hold position" behavior can be also applied to other species – there are five species in this game; undeads, orcs, night elves, humans and corrupted night elves. By the use of the state pattern, it is possible to save time and gain reusability and maintainability since you do not have to code the similar unit behaviors all over again for other species when programming such game.
Advantages of using State Pattern
1. State pattern allows object to perform state-specific behaviors and operations and partitions behavior based on its state.
State pattern is beneficial since the object's state-specific behaviors are maintained in a single object. It is much easier to create and add new states and transitions than extending behaviors using if or switch statements. New state implements the state interface, and new state can extend other states.
2. State pattern makes state transition explicit.
If the state is defined with an internal data values, its state transition do not have explicit representation. If a variable is used to specify its current state, it will be difficult to extend and maintain since the states and transitions are handled using many if and switch statements.
3. State objects can be shared by other classes.
As mentioned above, state object can be used by other classes. For example, all five species of the War Craft have common behaviors such as "Attack" and "Hold Position" behaviors, and those state-specified behaviors can be used by all character classes. Click the link below to see the examples.
State Pattern UML Diagram