标签:
<?php /** * 命令模式 * 将一个请求封装为一个对象从而使你可用不同的请求对客户进行参数化,对请求排除或记录请求日志,以及支持可取消的操作 */
//相当于一个命令寄存器,可以往里面写入命令,删除命令,或者说开始执行里面的所有命令 class Invoker { private $_command = array(); public function setCommand($command) //设置命令 { $this->_command[] = $command; } public function executeCommand()//执行命令 { foreach($this->_command as $command) { $command->execute(); } } public function removeCommand($command)//清除命令 { $key = array_search($command, $this->_command); if($key != false) { unset($this->_command[$key]); } } } // 命令接受者-具体执行命令里面操作的东西在这里写如,但它的执行与否,或者执行顺序 受 寄存器里写入的命令控制 class Receiver { private $_name = null; public function __construct($name) { $this->_name = $name; } public function action() { echo $this->_name." 执行攻击命令(action)<br />"; } public function action1() { echo $this->_name." 执行防御命令(action1)<br/>"; } } // 命令接口 配合具体命令,可以 来 集成 Receiver中不同的行为的组合 interface Command { public function execute(); } // 具体的命令 class ConcreteCommand implements Command { private $_receiver; public function __construct($receiver) { $this->_receiver = $receiver; } public function execute() { $this->_receiver->action(); } } // 具体命令1 class ConcreteCommand1 implements Command { private $_receiver; public function __construct($receiver) { $this->_receiver = $receiver; } public function execute() { $this->_receiver->action1(); } } // 具体命令2 class ConcreteCommand2 implements Command { private $_receiver; public function __construct($receiver) { $this->_receiver = $receiver; } public function execute() { $this->_receiver->action(); $this->_receiver->action1(); } } $objRecevier = new Receiver("小狗"); $objRecevier1 = new Receiver("刺蛇"); $objRecevier2 = new Receiver("雷兽"); $objCommand = new ConcreteCommand($objRecevier); $objCommand1 = new ConcreteCommand1($objRecevier); $objCommand2 = new ConcreteCommand($objRecevier1); $objCommand3 = new ConcreteCommand1($objRecevier1); $objCommand4 = new ConcreteCommand2($objRecevier2); // 使用 Recevier的两个方法 $objInvoker = new Invoker(); $objInvoker->setCommand($objCommand);//设置 小狗 攻击 $objInvoker->setCommand($objCommand1);//设置 小狗 防御 $objInvoker->executeCommand(); $objInvoker->removeCommand($objCommand1);//清除 小狗 防御 $objInvoker->executeCommand();//输出 $objInvoker->setCommand($objCommand2); //设置 刺蛇 攻击 $objInvoker->setCommand($objCommand3);//设置 刺蛇 防御 $objInvoker->setCommand($objCommand4);//设置 雷兽 攻击防御 $objInvoker->executeCommand();//输出 ?>
标签:
原文地址:http://www.cnblogs.com/jiufen/p/5026458.html