DotNetAge - Mvc & jQuery CMS
Hide sidebar

State


Definition


Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.

UML class diagram


state

Participants


The classes and/or objects participating in this pattern are:
  • Context
defines the interface of interest to clients

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

/// <summary>
/// The current inner state
/// </summary>
public IState State { get; set; }

/// <summary>
/// An inner counter of this context
/// </summary>
public int Counter { get; set; }

#endregion

#region Ctor

/// <summary>
/// Construct a new StateContext with the
/// given first state
/// </summary>
/// <param name="state">The first state of the object</param>
public StateContext(IState state)
{
State = state;
}

#endregion

#region Methods

/// <summary>
/// Send a request to be handled by the inner state
/// behavior
/// </summary>
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();




 


    Average:
  • Reads
    (1681)
  • Permalink
Share to: Add to del.icio.us Digg! Share on Google Buzz Share on Facebook Reddit! Stumble it! Share on Twitter

Tag cloud

Anything in here will be replaced on browsers that support the canvas element