Design Patterns

State



Design Pattern Type: Behavioral

GoF Statement of Intent:


Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.
Brief Overview:



Used to represent the state of an object. It is a clean way for an object to partially change its type at runtime.
UML Diagram:

Discussion and In-class Example:

In the State Design Pattern we used the example of the GumballMachine application in which we were creating a state machine. But each time we wanted to add a new state we had to change the code in several places in thethe GumballMachine class.

By isolating and encapsulating the states which have different behaviors we can hold within the GumballMachine an instance of each state object and then change the behavior of the GumballMachine by changing its state. This makes the GumballMachine appear to change its class. Note the similarity of this pattern to the Strategy pattern. The basic difference is that in the Strategy we decide at run time what behavior an object will exhibit and set that behavior dynamically, but it doesn't change. With the State pattern we can change the behavior dynamically.