State Design Pattern
State design pattern is used to change the behavior of object based on current state of object.
The intent is to change the behavior of the object as its state changes, and have the behavior reflected through classes.
- Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.
Handling of changes of behavior, based on state changes has to be run-time and using conditions for it will make the design
complex and inflexible.
- Object has different states and has to respond differently based on its current state.
Thus a separate class is required for different state, so that appropriate state object can be used based on the current state
- Have a separate abstract class for State, derive concrete class for each state and do the operation as required in
Where it is applicable?
- An object has to change its behavior at run-time based on its current state.
- Lot of conditional statements are used based on the state of object to do the operations.
How they work together?
- Context class provides the interface to client. It has instance of State object.
- State class provides interface Handle() for behavior.
- Concrete classes ConcreteStateA and ConcreteStateB represent different states and implement the method
Handle(), which does the operations based on current state.
- Client uses the context method Request() to do the operation, context uses the method Handle() with appropriate
concrete state object, based on its current state. ConcreteState object method Handle() does the operation applicable for
that state. The transition of state can be done in concrete State object or context.
- So the appropriate behavior has been chosen at run time, using concrete state object based on current state of object.
This also provides flexibility to add new state object and makes it easy for maintenance as conditional statements would
have increased the complexity as the number of states grow. Also it localizes the operation for behavior too, so it can be
Suresh Kumar Srivastava is founder of online learning site coursegalaxy.com and author of popular books "C In Depth",
"Data Structures Through C In Depth". He has 18+ years experience in industry and worked on architecture and design of
multiple products. This article is from his courses on design patterns.
Design Patterns in C#
Data Structures in Python