State

From CSSEMediaWiki
(Difference between revisions)
Jump to: navigation, search
(When to use it)
Line 7: Line 7:
 
== When to use it ==
 
== 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)
+
State should be used when:
  
If your code has groups of nested conditionals that all seem to check the same things but give different behavior you might need this.
+
*An object needs to change its behavior during runtime depending on the state it is in. (Anything that can be modeled as a state machine)
 +
 
 +
*Your code has groups of nested conditionals that provide different behavior depending on the state of the object.
  
 
== How it works ==
 
== How it works ==

Revision as of 03:27, 25 July 2009

Contents

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

State should be used when:

  • An object needs to change its behavior during runtime depending on the state it is in. (Anything that can be modeled as a state machine)
  • Your code has groups of nested conditionals that provide different behavior depending on the state of the object.

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.

State.jpg

See also


Personal tools