PHP设计模式之命令模式

以下文字部分均为本人自己的想法与总结所以未必正确;

参考

https://www.cnblogs.com/dawuge/p/9400831.html

https://github.com/flyingalex/design-patterns-by-php/blob/master/files/chapter23.md

定义:

将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤销的操作。是一种数据驱动的设计模式,它属于行为型模式,请求以命令的形式包裹在对象中,并传给调用对象。调用对象寻找可以处理该命令的合适的对象,并把该命令传给相应的对象,该对象执行命令。

优点:

1. 降低系统的耦合度

2. 新的命令可以很容易地加入到系统中

3. 可以比较容易地设计一个组合命令

缺点:

使用命令模式可能会导致某些系统有过多的具体命令类。

角色:

1. 接收者(Receiver)负责执行与请求相关的操作

2. 命令接口(Command)封装execute()、undo()等方法

3. 具体命令(ConcreteCommand)实现命令接口中的方法

4. 请求者(Invoker)包含Command接口变量

<?php
interface ICommand {
  function onCommand($name, $args);
}

class CommandChain {
    private $_commands = array();
    public function addCommand($cmd) {
        $this->_commands []= $cmd;
    }
    
    public function runCommand($name, $args) {
        foreach($this->_commands as $cmd) {
            if ($cmd->onCommand($name, $args)) return;
        }
    }
}

class UserCommand implements ICommand {
    public function onCommand($name, $args) {
        if ($name != 'addUser') return false;
        echo("UserCommand handling 'addUser'\n");
        return true;
    }
}

class MailCommand implements ICommand {
    public function onCommand($name, $args) {
        if ($name != 'mail') return false;
        echo("MailCommand handling 'mail'\n");
        return true;
    }
}

$cc = new CommandChain();
$cc->addCommand(new UserCommand());
$cc->addCommand(new MailCommand());
$cc->runCommand('addUser', null);
$cc->runCommand('mail', null);
?>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值