用 State Pattern 来实现一个简单的 状态机

首先要理解 State Pattern 模式。

http://www.dofactory.com/net/state-design-pattern

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 objects participating in this pattern are:

    • Context  (Account)
      • defines the interface of interest to clients
      • maintains an instance of a ConcreteState subclass that defines the current state.
    • State  (State)
      • defines an interface for encapsulating the behavior associated with a particular state of the Context.
    • Concrete State  (RedState, SilverState, GoldState)
      • each subclass implements a behavior associated with a state of Context

 

先画个状态机用来接收和处理数据。

 

开始定义Base状态和各个状态

    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;
        }

开始使用状态机

        static void Main(string[] args)
        {
            Monitor m = new Monitor();
            m.Start(); 
        }

 

转载于:https://www.cnblogs.com/fdyang/p/7127005.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值