`
qixin000
  • 浏览: 20979 次
  • 性别: Icon_minigender_1
  • 来自: 黑龙江
文章分类
社区版块
存档分类
最新评论

职责链的应用

阅读更多
在系统中经常要接收各方面的指令,解析指令后,交付一个处理程序进行统一处理,在这种情况下,如何系统设计不合理,就会出现众多的if-else,代码混乱不易扩展维护,所以采用职责链模式比较适合了!


例如,游戏中可能接受硬件指令,网络指令,手机指令,甚至其他,这都需要统一设计处理程序。

职责链模式本身比较简单。
但是要注意他和Filter模式的区别,Filter模式在处理指令时,是所有队列里面的所有filter处理器都会对指令进行处理。
职责链模式在处理指令的时候是:只要一个处理器处理了,那么程序就返回了,不继续处理了。

职责链基类
public abstract class ActionChainNode
    {
        protected static ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        private ActionChainNode next;

        public ActionChainNode AddChain(ActionChainNode next)
        {
            this.next = next;
            return next;
        }

        public bool Process(IGameState gameState, Action action)
        {
            try
            {
                bool processFlag = Do(gameState, action);
                if (!processFlag && next != null)
                {
                    processFlag = next.Process(gameState, action);
                    return processFlag;
                }
                return processFlag;
            }catch(Exception ex)
            {
                log.Error(ex.Message,ex);
            }
            return false;
        }

        protected abstract bool Do(IGameState gameState, Action action);
    }


一个指令处理器
internal class Action上分:ActionChainNode
    {
        private IPortService logic;
        private IPersistService persist;
        protected override bool Do(IGameState gameState, Action action)
        {
            logic = gameState.PortService;
            if (action.Sender == PlayPort.ControlPanel)
            {
                persist = gameState.PersistService;
                if (action.Command.Code == (short) CommandCode.上分)
                {
                    ThreadPool.QueueUserWorkItem(new WaitCallback(Doo), action);
                    return true;
                }
            }
            return false;
        }

        private void Doo(object state)
        {
        }
}



另一个处理器实例
internal class Action心跳 : ActionChainNode
    {
        private IPortService logic;
        public Action心跳()
        {
            log.Info("**【启动】心跳!!");
            Timer timer = new Timer(1000);
            timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
            timer.Enabled = true;
        }
        protected override bool Do(IGameState gameState, Action action)
        {
            logic = gameState.PortService;
            return true;
        }

        void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            if(logic!=null)
            {
                ICommand heart = SingleCommand.Instance[CommandCode.心跳];
                heart.Data = new int[] {  };
                logic.Write(new Action(PlayPort.Logic, PlayPort.ControlPanel, heart));
            }
        }
    }


将他们连一块
public class GlobalActionChainFactory
    {
        private static GlobalActionChainFactory globalActionChainFactory = new GlobalActionChainFactory();
        private ActionChainNode root;
        private GlobalActionChainFactory()
        {
            root = new Action1();
            ActionChainNode next = root.AddChain(new Action2())
                .AddChain(new Action3()).AddChain(new Action4())
                .AddChain(new Action5()).AddChain(new Action6())
                .AddChain(new Action7());

            next.AddChain(new Action8());
        }
        public static GlobalActionChainFactory Instance
        {
            get
            {
                return globalActionChainFactory;
            }
        }
        public static ActionChainNode GetChain()
        {
            return Instance.root;
        }
    }


也可以再根据情况构建另一个处理职责链,然后就可以将它们放在系统的不同状态中,接收来自各方面的指令了。
例如,一个系统等待状态,在这等待期间会接受很多指令,她要处理
public class StepWaitingState : AbstractSingleGameState
    {
        public override GameState CurrentState
        {
            get { return GameState.StepWaiting; }
        }
       
        private Timer timer = new Timer(1000);
        private GameWait wait;
        public StepWaitingState()
        {
            timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
        }
        
        public override object Enter(Action action)
        {
            try
            {
                Tag.Clear();
                logic.Write(new Action(PlayPort.Logic, SingleCommand.SimpleCommand("等待期", "等待期")));
                timer.Enabled = true;
                //
                wait = GameWait.Instance;
                wait.Waiting();
                timer.Enabled = false;
                log.Debug("==========waiting finished ==============");
                //
                ActionFilterChainNode filter = StepPostFilterFactory.GetChain();
                filter.Process(this, action);
                //
                ICommand command = SingleCommand.Instance[CommandCode.某指令];
                command.Data = SingleGameContext.WinCard;
                logic.Write(new Action(LOGIC_PORT, command));
                command.Data = SingleGameContext.WinCard.ToColorTextString();
                logic.Write(new Action(LOGIC_PORT, UDP_PORT, command));
                //等待界面回应
                wait = GameWait.Instance;
                Tag.Add("open wait", wait);
                wait.Waiting();

                Transit(action);
            }
            catch (Exception ex)
            {
                log.Error(ex.Message,ex);
            }
            return null;
        }

        protected override void OnPortEvent(object sender, Action action)
        {
            Doo(action);
        }

        private void Doo(object state)
        {
            Action action = (Action) state;
            ActionChainNode controlPanelActionChain = WatingActionChainFactory.GetChain();
            controlPanelActionChain.Process(this, action);
        }

        public override IGameState Transit(Action action)
        {
            if (GameContext.GameState.CurrentState == CurrentState)
                GameContext.SetState(StateFactory.StepPost, action);
            return GameContext.GameState;
        }

    }


其中这行代码

ActionChainNode controlPanelActionChain = WatingActionChainFactory.GetChain();


就是一个职责链实例,
controlPanelActionChain.Process(this, action);

通过process进行处理,处理完毕返回!
其中的基类AbstractSingleGameState是状态模式的一个类型,下一个文章说一下状态模式的应用!

其中的
ActionFilterChainNode filter = StepPostFilterFactory.GetChain();

是Filter模式
public abstract class ActionFilterChainNode
    {
        protected static ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        private ActionFilterChainNode next;

        public ActionFilterChainNode AddChain(ActionFilterChainNode next)
        {
            this.next = next;
            return next;
        }

        public void Process(IGameState gameState, Action action)
        {
            try
            {
                Do(gameState, action);
                if (next != null)
                    next.Process(gameState,action);
            }catch(Exception ex)
            {
                MessagePrompt.Alert(this,"出现异常!" + Environment.NewLine + ex.Message);
            }
        }

        protected abstract void Do(IGameState gameState, Action action);
    }


可以看出来他是连续处理的,直到filter链的最后一个处理器

现在尅看出来,如果要扩展处理器,只要实现一个ActionChainNode就可以了,然后挂到相应的职责链上就可以了,代码清晰,以维护,扩展性强。

完毕!
http://qixin000.iteye.com/blog/1491198
分享到:
评论

相关推荐

    JavaScript设计模式之职责链模式应用示例

    主要介绍了JavaScript设计模式之职责链模式,结合实例形式分析了javascript责任链模式的概念、原理、使用方法及相关操作注意事项,需要的朋友可以参考下

    iOS应用设计模式开发中职责链(责任链)模式的实现解析

    主要介绍了iOS应用设计模式开发中职责链模式的相关实现解析,示例代码为传统的Objective-C,需要的朋友可以参考下

    20职责链模式1

    定义使多个对象都有机会处理请求,从而避免请求的发送者和接受者之间的耦合关系。将这个对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。UML应用场

    享元、解释器、职责链、装饰模式

    考虑这样一个实际应用:就是如何实现灵活的奖金计算。 奖金计算是相对复杂的功能,尤其是对于业务部门的奖金计算方式,是非常复杂的,除了业务功能复杂外,另外一个麻烦之处是计算方式还经常需要变动,因为业务...

    实例讲解C#中的职责链模式

    大家好,欢迎来到老胡的博客,今天我们继续了解设计模式中的职责链模式,这是一个比较简单的模式。跟往常一样,我们还是从一个真实世界的例子入手,这样大家也对这个模式的应用场景有更深刻的理解。 一个真实的栗子 ...

    C#设计模式之ChainOfResponsibility职责链模式解决真假美猴王问题实例

    本文实例讲述了C#设计模式之ChainOfResponsibility职责链模式解决真假美猴王问题。分享给大家供大家参考,具体如下: 一、理论定义 职责链模式 向一个 对象提出一个请求,如果这个对象无法处理这个请求,将指定下一...

    物联网技术在果蔬冷链物流中的应用研究

    果蔬冷链物流的目的是保证果蔬从田间到消费者手中品质良好, 但流通中, 经常出现各环节衔接断裂, 造成果蔬冷链物流成本较高、品质难保证、职责划分不清等现象。物联网技术应用在果蔬冷链物流中, 可以实现监管部门...

    Java模式开发之责任链模式

    从击鼓传花谈起 击鼓传花是一种热闹而又紧张的饮酒游戏。在酒宴上宾客依次坐定位置,由一人击鼓,击鼓的地方与传花... 击鼓传花便是责任链模式的应用。在责任链模式里,很多的对象由每一个对象对其下家的引用而联接起

    77丨开源实战一(下):通过剖析JavaJDK源码学习灵活应用设计模式1

    模板模式在 Collections 类中的应用我们前面提到,策略、模板、职责链三个模式常用在框架的设计中,提供框架的扩展点,让框架使用者,在不修改框架源码的情况

    Java经典设计模式之责任链模式原理与用法详解

    主要介绍了Java经典设计模式之责任链模式,简单说明了责任链模式的概念、原理,并结合实例形式分析了java实现责任链模式的具体用法与相关注意事项,需要的朋友可以参考下

    果蔬冷链物流现状分析和物联网技术在果蔬冷链物流中的应用

    本文以果蔬冷链物流为研究对象, 物联网的技术应用到果蔬冷链物流各环节中, 构建物联网技术在果蔬冷链物流中应用总体架构。1 果蔬冷链物流现状分析目前我国果蔬种植面积和产量均居, 每年约有4亿吨生鲜农产

    《c#设计模式》电子书+随书源码

    本书内容覆盖了所有23个经典的“四人小组”设计模式,具体包括:适配器,外观,合成,桥接,单件,观察者,中介者,代理,职责链,享元,生成器,工厂方法,抽象工厂,原型,备忘录,模板方法,状态,策略,命令,...

    UML基础、案例与应用(第三版)].施穆勒.扫描版_2分.pdf

    22.3.2 职责链模式:Web浏览器事件模型 257 22.4 我们自己的设计模式 258 22.5 使用设计模式的好处 260 22.6 小结 260 22.7 常见问题解答 261 22.8 小测验和习题 261 22.8.1 小测验 261 22.8.2 习题 261 第三部分 ...

    simplecalculator:使用责任链模式的简单计算器

    使用责任链模式或 RPN(反向波兰表示法)的简单计算器 应用程序可以将带有操作的文件作为参数 例子 : java -jar ./target/simplecalculator-1.0-SNAPSHOT.jar ./src/main/resources/myCalcFile.txt

    Learning+PHP设计模式

    通过学习如何在代码中使用设计模式,可以更高效地构建服务器端应用,在这个过程中,你的PHP编程水平也将逐步提高。本书利用大量浅显易懂的例子告诉你如何...第13章 职责链设计模式 第14章 利用观察者模式构建多设备CMS

    java设计模式

    16.3 责任链模式的应用 16.3.1 责任链模式的优点 16.3.2 责任链模式的缺点 16.3.3 责任链模式的注意事项 16.4 最佳实践 第17章 装饰模式 17.1 罪恶的成绩单 17.2 装饰模式的定义 17.3 装饰模式应用 17.3.1 装饰模式...

    C#设计模式:责任链模式

     责任链模式是指一个处理需要涉及多个过程或者角色参与处理,并基于某个约定组成一个链,每个过程或者角色拥有各自职责进行处理。责任链模式有效组织一个过程处理,同时子过程之间职责明确。在.NET平台中很常见此...

Global site tag (gtag.js) - Google Analytics