将请求封装成对象,以便使用不一样的请求、队列或者日志来参数化其余对象。命令模式也支持可撤销的操做。
从而实现“行为请求者”与“行为实现者”的松耦合。php
抽象命令(Command):定义命令的接口,声明执行的方法(execute、undo)
具体命令(ConcreteCommand):命令接口实现对象,一般会持有接收者,并调用接收者的功能来完成命令要执行的操做
接收者(Receiver):执行命令的对象
请求者(Invoker):调用命令对象执行请求编程
<?php /** * 抽象命令(Command) * Interface Command */ interface Command{ /** * 执行接口 * @return mixed */ public function execute(); /** * 撤销接口 * @return mixed */ public function undo(); } /** * 命令接收者(Receiver) * Class Light */ class Light{ public function on(){ echo 'light on'; } public function off(){ echo 'light off'; } } /** * 具体命令(ConcreteCommand) * Class LightOn */ class LightOn implements Command{ private $light; public function __construct(Light $light) { $this->light = $light; } public function execute() { $this->light->on(); } public function undo() { $this->light->off(); } } /** * 具体命令(ConcreteCommand) * Class LightOff */ class LightOff implements Command{ private $light; public function __construct(Light $light) { $this->light = $light; } public function execute() { $this->light->off(); } public function undo() { $this->light->on(); } } /** * 请求者(Invoker) * Class Control */ class Control{ protected $object; public function __construct($object) { $this->object = $object; } public function exec(){ $this->object->execute(); } public function undo(){ $this->object->undo(); } } $light = new Light(); $light_on = new LightOn($light); $control = new Control($light_on); $control->exec(); echo '<br />'; $control->undo();
1.封装变化
2.多用组合,少用继承
3.针对接口编程,不针对实现编程
4.为交互对象之间松耦合设计而努力
5.类应该对扩展开放,对修改关闭
6.依赖抽象、不要依赖具体类设计模式
1.命令模式将发出请求的对象和执行请求的对象解耦
2.在被解耦的二者之间经过命令对象进行沟通。命令对象封装了接收者和一个或一组动做
3.调用者经过调用命令对象的execute方法发出请求,这样使得接受者的动做被调用
4.调用者能够接受命令当作参数,甚至在运行时动态的进行
5.命令能够支持撤销,作法实现一个undo的方法来回到execute被执行前的状态
6.命令也能够用来实现日志、事物系统、队列this
参考文献《head first设计模式》spa