State Design Pattern


GoF Statement: Allows an object to alter its behavior when its internal state changes. The object will appear to change its class.
Category: Behavioral
UML Diagram:  

Description of the Demonstration:

In this demonstration an instance of the GumballMachine class implements a state machine, but all of the states are defined by instances of sub-classes of the State class. When a function is called in the GumballMachine, like GumballMachine::insertQuarter(), the GumballMachine just calls insertQuarter on its current State object. The State object knows how to handle each of the transition actions. Some of those actions will be invalid for certain states, e.g. you can't insert a quarter when one has already been inserted, a valid transition action will be handled by a State telling the GumballMachine what State to change to.

In essence what is happening is that the behavior of the GumballMachine is being dynamically changed while the application is running. Some software engineers consider the State Design Pattern a variation of the Strategy pattern. The main difference being that the external class that implements the behavior of a class changes dynamically at run time with the State Design Pattern.



Code:

Click here to download a zip file containing all the source files and an executable of the Demonstration. See the _ReadMe.txt file in the zip.