以下文字部分均为本人自己的想法与总结所以未必正确;
参考
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);
?>