Definition
Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.
UML class diagram
Participants
The classes and/or objects participating in this pattern are:
- Context
maintains an instance of a ConcreteState subclass that defines the current state.
- State - defines an interface for encapsulating the behavior associated with a particular state of the Context.
- Concrete State - each subclass implements a behavior associated with a state of Context
Sample code in C#
#region State
public interface IState
{
void Handle(StateContext context);
}
#endregion
#region Context
public class StateContext
{
#region Properties
///
/// The current inner state
///
public IState State { get; set; }
///
/// An inner counter of this context
///
public int Counter { get; set; }
#endregion
#region Ctor
///
/// Construct a new StateContext with the
/// given first state
///
/// The first state of the object
public StateContext(IState state)
{
State = state;
}
#endregion
#region Methods
///
/// Send a request to be handled by the inner state
/// behavior
///
public void Request()
{
State.Handle(this);
}
#endregion
}
#endregion
#region Concrete State
public class ConcreteStateA : IState
{
#region IState Members
public void Handle(StateContext context)
{
context.Counter += 2;
// change the context state to a new state
context.State = new ConcreteStateB();
}
#endregion
}
public class ConcreteStateB : IState
{
#region IState Members
public void Handle(StateContext context)
{
context.Counter -= 1;
// change the context state to a new state
context.State = new ConcreteStateA();
}
#endregion
}
#endregion
The implementation of state depends on inheritance. The main issues is to understand that every concrete state is responsible to change the current context behavior to the next context behavior in the chain of behaviors. The
example I gave is simple and can be run with this code
// initialize a context with a first state behavior
StateContext context = new StateContext(new ConcreteStateA());
context.Request();
Console.WriteLine("The current counter need to be 2: {0}", context.Counter);
context.Request();
Console.WriteLine("The current counter need to be 1: {0}", context.Counter);
context.Request();
Console.WriteLine("The current counter need to be 3: {0}", context.Counter);
Console.Read();
-
-
Liest(1541)
-
Permalink