The state pattern is a behavioural software design pattern that implements a state machine in an object-oriented way. With the state pattern, a state machine is implemented by implementing each individual state as a derived class of the state pattern interface and implementing state transitions by invoking methods defined by the pattern's superclass.
The state pattern can be interpreted as a strategy pattern which is able to switch the current strategy through invocations of methods defined in the pattern's interface.
This pattern is used in computer programming to encapsulate varying behaviour for the same object based on its internal state. This can be a cleaner way for an object to change its behaviour at runtime without resorting to large monolithic conditional statements and thus improve maintainability.
The State design pattern is one of the twenty-three well-known GoF design patterns that describe how to solve recurring design problems to design flexible and reusable object-oriented software, that is, objects that are easier to implement, change, test, and reuse.
What problems can the State design pattern solve?
An object should change its behaviour when its internal state changes.
State-specific behaviour should be defined independently. That is, new states should be added and the behaviour of existing states should be changed independently.
Implementing state-specific behaviour directly within a class is inflexible because it commits the class to a particular behaviour and makes it impossible to add a new state or change the behaviour of an existing state later independently from (without changing) the class.
What solution does the State design pattern describe?
Define separate (state) objects that encapsulate state-specific behaviour for each state. That is, define an interface (State) for performing the state-specific behaviour, and define classes that implement the interface for each state.
A class delegates state-specific behaviour to its current state object instead of implementing state-specific behaviour directly.
This makes a class independent of how state-specific behaviour is implemented. New states can be added by defining new state classes.
A class can change its behaviour at run-time by changing its current state object.
source : wiki



