State

From CSSEMediaWiki
(Difference between revisions)
Jump to: navigation, search
(When to use it)
Line 21: Line 21:
  
 
[[Image: State.jpg]]
 
[[Image: State.jpg]]
 +
 +
==Participants==
 +
===Context===
 +
This class will be called by clients and provides methods of interest to them. It also holds a ConcreteState applicable to the current state and passes on state-specific requests to the current ConcreteState.
 +
 +
===State===
 +
This class defines an interface for the behavior associated with a particular state.
 +
 +
===ConcreteState===
 +
Each ConcreteState implements the behavior applicable to a particular object state.
 +
 +
Either ConcreteState or the Context may decide which states follow which other states and under what circumstances.
  
 
== See also ==
 
== See also ==

Revision as of 03:32, 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

Participants

Context

This class will be called by clients and provides methods of interest to them. It also holds a ConcreteState applicable to the current state and passes on state-specific requests to the current ConcreteState.

State

This class defines an interface for the behavior associated with a particular state.

ConcreteState

Each ConcreteState implements the behavior applicable to a particular object state.

Either ConcreteState or the Context may decide which states follow which other states and under what circumstances.

See also


Personal tools