Saturday, July 28, 2007

Sate Design Pattern

Every developer has implemented a finite state machine at least once in his or her career. You can't avoid them—they are everywhere, and not just limited to the world of software development.The ability to add more states to the design of a finite automaton is often an unwritten requirement, and implementations are frequently modified when requests for additional states and transitions arrive. If you've got a good design, you can anticipate and account for such changes. More importantly, behavior and operations specific to any state in a finite state machine should be confined and localized to the representation of that state. In other words, state-specific code lives in an object that implements that state. This, in turn, allows you to add new states and transitions easily

namespace State_Pattern
{
public abstract class State
{
public abstract void Handle(Context context);

}

public class Context
{
State state;

public State State
{
get { return state; }
set { state = value; }
}
public Context()
{
this.state = new ConcreteStateA();

}

public void Handle()
{
state.Handle(this);
}

}

public class ConcreteStateA:State
{

public override void Handle(Context context)
{


Console.WriteLine("i am in Concrete A" );
context.State = new ConcreteStateB();
}
}

public class ConcreteStateB : State
{
public override void Handle(Context context)
{
Console.WriteLine("i am in Concrete B" );
context.State = new ConcreteStateA();
}
}
}

class Program
{
static void Main(string[] args)
{
Context context = new Context();
for(int a =0 ; a<10;a++)
context.Handle();
Console.ReadLine();



}
}

No comments: