首先要理解 State Pattern 模式。
創(chuàng)新互聯(lián)公司專業(yè)為企業(yè)提供烈山網(wǎng)站建設(shè)、烈山做網(wǎng)站、烈山網(wǎng)站設(shè)計、烈山網(wǎng)站制作等企業(yè)網(wǎng)站建設(shè)、網(wǎng)頁設(shè)計與制作、烈山企業(yè)網(wǎng)站模板建站服務(wù),10多年烈山做網(wǎng)站經(jīng)驗,不只是建網(wǎng)站,更提供有價值的思路和整體網(wǎng)絡(luò)服務(wù)。http://www.dofactory.com/net/state-design-pattern
The classes and objects participating in this pattern are:
先畫個狀態(tài)機用來接收和處理數(shù)據(jù)。
開始定義Base狀態(tài)和各個狀態(tài)
public abstract class StateBase
{
public abstract void Enter(Monitor context);
public virtual void Exit(Monitor context)
{
Console.WriteLine("Exiting current state: {0}", context.CurrentState.StateName);
}
public string StateName
{
get;
set;
}
}
public class ConnectState : StateBase
{
public ConnectState()
{
this.StateName = "Connect";
}
public override void Enter(Monitor context)
{
Console.WriteLine("Enter - {0}", context.CurrentState.StateName);
context.MoveToNextState(new ReceiveDataState());
}
}
Create a context class, and set initial state to start running.
public class Monitor
{
public Monitor()
{
}
public void MoveToNextState(StateBase nextState)
{
Console.WriteLine("Changing state...");
this.CurrentState.Exit(this);
this.CurrentState = nextState;
this.CurrentState.Enter(this);
}
public void Start()
{
this.CurrentState = new NotStartState();
this.CurrentState.Enter(this);
}
public StateBase CurrentState
{
get;
set;
}
開始使用狀態(tài)機
static void Main(string[] args)
{
Monitor m= new Monitor();
m.Start();
}