State
Line 17: | Line 17: | ||
− | + | [[Image: State.jpg]] | |
− | + | ||
− | + | ||
− | + | ||
− | + | ||
− | + | ||
− | + |
Revision as of 21:40, 6 October 2008
Intent
To allow an object to change its behavior when the state of the object changes. When the object changes behavior it will appear to change class.
When to use it
When an object needs to change its behavior during runtime dependent on the state it is in. (Anything that can be modeled as a state machine)
If your code has groups of nested conditionals that all seem to check the same things but give different behavior you might need this.
How it works
One abstract State class is introduced containing the common interface for all the states. Every different behavior is represented as a new subclass of this State class.
The object needing the state behavior creates and initalises one instance of each state and uses a common reference to point to the current state. Now the object can access the appropriate behavior through the common interface of the State class.