大头

设计模式之命令链模式

概念

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

实现

<?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);
posted @ 2017-04-19 19:55  and大头  阅读(1378)  评论(0编辑  收藏  举报

大头