zoukankan      html  css  js  c++  java
  • 设计模式之命令链模式

    概念

    命令链 模式以松散耦合主题为基础,发送消息、命令和请求,或通过一组处理程序发送任意内容。每个处理程序都会自行判断自己能否处理请求。如果可以,该请求被处理,进程停止。您可以为系统添加或移除处理程序,而不影响其他处理程序。(自己理解还是有点含糊)。

    实现

    <?php
    /**
     * Created by PhpStorm.
     * User: ASUS
     * Date: 2017-04-19
     * Time: 19:25
     * 命令链模式
     */
    //定义命令接口
    interface  commond
    {
        public function onCommond($name,$args);
    }
    
    //定义命令(说处理器更加合理)集合
    class CommondChain
    {
        //定义装在命令容器
        private $commonds = array();
    
        //添加命令
        public function addCommond($cmd)
        {
            $this->commonds[] = $cmd;
        }
        //运行命令
        public function runCommond($name,$args){
            //通过遍历处理器集合,判断是否执行这次请求
            foreach ($this->commonds as $commond){
                if($commond->onCommond($name,$args)){
                    return ;
                }
            }
        }
    }
    //实现命令接口
    class Student implements commond{
    
        public function  onCommond($name, $args)
        {
            // TODO: Implement onCommond() method.
            if($name == 'student'){
                echo '大学生借书不能超过十本';
                return true;
            }
            return false;
        }
    }
    
    class  Graduate implements  commond {
        public  function  onCommond($name, $args)
        {
            // TODO: Implement onCommond() method.
            if($name == "graduate"){
                echo '研究生借书可以超过十本';
                return true;
            }
            return false;
        }
    }
    $cmdchain = new CommondChain();
    //添加处理器
    $cmdchain->addCommond(new Student());
    $cmdchain->addCommond(new Graduate());
    //运行处理器
    $cmdchain->runCommond('student',null);
    $cmdchain->runCommond('graduate',null);
  • 相关阅读:
    「十二省联考2019」 春节十二响
    「八省联考2018」 劈配
    斯特林数
    「POJ2505」A multiplication game [博弈论]
    [luogu2048] [bzoj2006] [NOI2010] 超级钢琴 题解
    [HNOI2002]-洛谷2234-营业额统计-Treap
    平衡树Treap模板与原理
    KMP算法讲解
    高斯消元--模板,原理
    第一篇博客!!
  • 原文地址:https://www.cnblogs.com/webph/p/6735292.html
Copyright © 2011-2022 走看看