1.命令模式的概念:
将请求封装成对象,这样可以让你使用不同的请求、队列、或者日志请问来参数化其他对象。命令模式也支持撤销操作。
2.命令模式的结构图
3.命令模式角色说明
调用者(invoker)角色:这个调用者持有一个命令对象,并在某个时刻调用命令对象的excute()方法,将请求付诸实行。
命令(command)角色:为所有的命令声明一个接口,调用命令对象的excute()方法,就可以让接收者进行先关的动作。这个接口也具备一个undo()方法。调用者(invoker)角色:这个调用者持有一个命令对象,并在某个时刻调用命令对象的excute()方法,将请求付诸实行。
具体命令(ConcreteCommand)角色:定义了动作和接收者之间的绑定关系。
接收者(receiver)角色:这个接收者知道如何进行必要的工作。
4.命令模式的实现
<?php /** * Created by PhpStorm. * User: Administrator * Date: 16-10-21 * Time: 上午10:19 */ /* * 抽象命令接口 */ interface Command { public function execute(); public function undo(); } /* * 具体命令 */ Class ConcreteCommand1 implements Command{ public $receiver; public function __construct($receiver){ $this->receiver = $receiver; } public function execute(){ $this->receiver ->action(); } public function undo(){ echo ‘取消concreteCommand1 操作<br>‘; } } /* * 具体命令 */ Class NoCommand implements Command{ public function __construct(){ } public function execute(){ echo ‘no command<br>‘; } public function undo(){ echo ‘no undo<br>‘; } } /* * 具体命令 */ Class ConcreteCommand2 implements Command{ public $receiver; public function __construct($receiver){ $this->receiver = $receiver; } public function execute(){ $this->receiver ->action(); } public function undo(){ $this->receiver ->action1(); } } /* * 接收者 */ Class Receiver1{ public function action(){ echo ‘Receiver1 action<br>‘; } public function action1(){ echo ‘取消 Receiver1 action<br>‘; } } /* * 接收者 */ Class Receiver2{ public function action(){ echo ‘Receiver2 action‘; } public function action1(){ echo ‘取消 Receiver2 action‘; } } /* * 调用者 */ Class Invoker{ public $commandArr = array(); public $undoCommand; public function __construct(){ for($i=0;$i<=1;$i++){ $this->commandArr[$i] = new NoCommand(); } $this->undoCommand = new NoCommand(); } public function setCommand($slot,$command){ $this->commandArr[$slot] = $command; } public function executeCommand($slot){ $this->commandArr[$slot]->execute(); $this->undoCommand = $this->commandArr[$slot]; } public function undoCommand(){ $this->undoCommand->undo(); } } //客户端操作 $invoker = new Invoker(); $invoker->setCommand(0,new ConcreteCommand1(new Receiver1())); $invoker->setCommand(1,new ConcreteCommand1(new Receiver2())); $invoker->executeCommand(0); $invoker->undoCommand();
时间: 2024-11-09 08:09:12