The State pattern allows an object to alter its behavior when its internal state changes. The object appears to change its class.
The Figure illustrates the State Pattern.
The following lists the benefits of using the State pattern:
Localizes state-specific behavior and partitions behavior for different states .
Make state transitions explicit.
When to Use:
You should use the State pattern when:
An object's behavior depends on its state and it must change its behavior at run-time depending on that state.
Operations have large conditional statements that consist of multiple states and depend on the object's state.
The State design pattern is one of the most useful patterns of those described within the Gang of Four.
Games often depend on the State pattern because objects can change states so frequently in games.
The purpose of the State pattern is to allow an object to change its behavior when the state changes.
Many other simulations, whether they are games or
not, depend on the State pattern as well.
The Figure below shows the basic design pattern in a class diagram.
As shown, there is no Client class. However, the GoF book says that the Context is the primary interface for the clients. When examining the pattern, think of the Client class making its request through the Context class. There is a lot to understanding and effectively using the State design pattern, so for now, just take a quick look at the class diagram; the details will be unrolled gradually.