Use this tag for questions relating to the State design pattern, one of the Gang of Four's behavioral design patterns. Also consider using the [design-patterns] tag and a programming language tag if applicable.
According to the GoF book (page 305) the purpose of the State design pattern is to,
Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.
There are two scenarios where the State design pattern is applicable (page 306).
- An object's behavior depends on its state, and it must change its behavior at run-time depending on that state.
- Operations have large, multipart conditional statements that depend on the object's state. This state is usually represented by one or more enumerated constants. Often, several operations will contain this same conditional structure. The State pattern puts each branch of the conditional in a separate class. This lets you treat the object's state as an object in its own right that can vary independently from other objects.
There are three consequences of applying the State design pattern (page 307).
- It localizes state-specific behavior and partitions behavior for different states.
- It makes state transitions explicit.
- State objects can be shared.
For details about the structure and implementation of the State design pattern, see the following online resources.
Note the design-patterns tag encompasses this pattern as well as the other 22 patterns from the GoF book. Consider using any of these tags in combination, as applicable.