• 状态机学习


    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace StateMachine
    {
        class Program
        {
            static void Main(string[] args)
            {
                var door = new Door(State.Open);
    
                while (true)
                {
                    string s = Console.ReadLine();
                    Operation op = string.IsNullOrEmpty(s) ? Operation.Push : Operation.Pull;
                    door.Process(op);
                }
            }
        }
    
        enum Operation
        {
            Push, Pull
        }
    
        enum State
        {
            Open, Closed
        }
    
        class Door
        {
            public State State { get; set; }
    
            Dictionary<State, Dictionary<Operation, Action>> rule;
            public Door(State state)
            {
                this.State = state;
    
                rule = new Dictionary<State, Dictionary<Operation, Action>>();
                foreach (var e in Enum.GetValues(typeof(State)))
                {
                    rule[(State)e] = new Dictionary<Operation, Action>();
                }
    
                InitOperationRule();
            }
    
            void InitOperationRule()
            {
                //正常操作
                rule[State.Closed][Operation.Push] = () => { Console.WriteLine("门被推开了"); State = State.Open; };
                rule[State.Open][Operation.Pull] = () => { Console.WriteLine("门被拉上了"); State = State.Closed; };
    
                ////加入几种特殊情况的处理
                //rule[State.Closed][Operation.Pull] = () => Console.WriteLine("门是关上的,拉了也白拉");
                //rule[State.Open][Operation.Push] = () => Console.WriteLine("门是开的,不用推了,直接进去吧");
            }
    
            public void Process(Operation op)
            {
                try
                {
                    rule[State][op]();
                }
                catch (KeyNotFoundException)
                {
    
                    Console.WriteLine(string.Format("门在{0}状态下不允许{1}操作", State, op));
                }
                
            }
        }
    }
  • 相关阅读:
    C#编写的windows程序随系统启动
    CentOS 6.0修改ssh远程连接端口
    C# 控件缩写大全+命名规范+示例
    记录点滴
    C++封装,继承,多态,友元
    策略模式
    OpenGL入门
    C++四种类型转换
    观察者模式Observer Pattern
    双向链表std::list和单向链表std::forward_list
  • 原文地址:https://www.cnblogs.com/EthanSun/p/3156144.html
Copyright © 2020-2023  润新知