欢迎您来到GIS动力

加入收藏 免费注册 用户登陆 帮助中心
首页 新闻动态 技术专栏 银杏树下 学习考研 软件下载 求职招聘 许愿瓶 节日祝福 用户中心 精彩推荐 资源搜索 地图
专栏导航: AO开发 | SO开发 | ArcGIS桌面 | 超图桌面 | 开发语言 | 数据库 | WebGIS | 银杏文学 | 研究生考题 | FreeMap FreeTalk
   您现在位于: 首页技术专栏开发语言 → 正文
C# 3.0下有限状态机的一种优雅的实现
08-08-15 16:54:38 作者:天方 出处:http://www.cnblogs.com/TianFang

C# 3.0下有限状态机的一种优雅的实现

实现状态机有多种模式,其中最灵活而强大的方式是通过迁移表来实现,该方式的缺点之一是需要编写大量小块代码去支持迁移表。而在C#3.0中,可以以一种非常优雅的方式实现。

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

9 7 3 1 2 4 8 :

(本文已被浏览 次)
发布人:admin
推荐给好友:发送给好友
上篇新闻:
下篇新闻:
相关评论
发表我的评论
  • 尊重网上道德,遵守《全国人大常委会关于维护互联网安全的决定》及中华人民共和国其他各项有关法律法;
  • 本站有权保留或删除您发表的任何评论内容;
  •   相关文章  
    无相关新闻

    关于我们友情链接 ┋ 与我在线 ┋ 管理 ┋ TOP
     
    网站当前版本:GisPower CMS V3.0
    『GIS 动力』- http://www.gispower.org/
    联系我们:webmaster#gispower.org
    Copyright (c) 2003-2007 GisPOwer.Org. All Rights Reserved.
     

                   滇ICP备05006901号