State design pattern is used to change the behavior of object based on current state of object.
Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.
The intent is to change the behavior of the object as its state changes, and have the behavior reflected through classes.
Object has different states and has to respond differently based on its current state.
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.
Have a separate abstract class for State, derive concrete class for each state and do the operation as required in
Thus a separate class is required for different state, so that appropriate state object can be used based on the current state
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.
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.
How they work together?
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.
CourseGalaxy is focused on transformation of Engineering graduate to Software Engineer to fill the gap
between education and industry and provide the training on specific problems of industry to enhance the skills
of Engineers in industry to do their job appropriately.