State pattern dynamically changes the state class and its behabior when its internal state changes.
What is the practical usage of this pattern? I have no idea where in NET framework this pattern is applied. I do know that it is very useful and practical to apply this pattern when one needs to dynamically change class represented by a state
Let's look at the coding structure of this pattern:
using System;
abstract class State
{
abstract public void ChangeState(Context context);
abstract public string Message();
}
class SleepyState : State
{
override public void ChangeState(Context context)
{
context.State = new WakeupState();
}
override public string Message()
{
return "I'm sleeping";
}
}
class WakeupState : State
{
override public void ChangeState(Context context)
{
context.State = new EnergizedState();
}
override public string Message()
{
return "I'm waking up";
}
}
class EnergizedState : State
{
override public void ChangeState(Context context)
{
context.State = new SleepyState();
}
override public string Message()
{
return "I'm energized";
}
}
class Context
{
public Context(State state)
{
this.state = state;
}
private State state;
public State State
{
get{ return state; }
set{ state = value; }
}
public void Request()
{
state.ChangeState( this );
}
public void Show()
{
Console.WriteLine( "State: " + state.Message() );
}
}
public class Client
{
public static void Main( string[] args )
{
// Start with SleepyState
Context c = new Context(new SleepyState() );
c.Show();
// Change to WakeupState
c.Request();
c.Show();
// Change to EnergizedState
c.Request();
c.Show();
// Go back to SleepyState
c.Request();
c.Show();
}
}
Here is a summary of the structural concept of the State pattern:
1. Create an abstract base class and its common interface
2. Create concrete sub classes overriding the require methods, especially the method to actually change the state and class
3. Create a stand alone class (Context or any name you prefer) to hold the current state and also provides logic to change to a different state
4. Client can now instantiate the context object, request a change from one state to another
Anyone has any idea to use it differently or has a different view about this pattern, love to hear from you.
Hope it helps