php 设计模式之命令模式

命令模式

将一个请求封装为一个对象,从而使用户可用不同的请求对客户进行参数化。对请求排队或记录请求日志,以及支持撤销的操作。

命令模式以松散耦合主题为基础,发送消息、命令和请求,或通过一组处理程序发送任意内容。每个处理程序都会自行判断自己能否处理请求。如果可以,该请求被处理,进程停止。您可以为系统添加或移除处理程序,而不影响其他处理程序。

命令模式的四种角色:

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

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

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

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

 

 1 <?php
 2 interface ICommand {
 3   function onCommand($name, $args);
 4 }
 5 
 6 class CommandChain {
 7     private $_commands = array();
 8     
public function addCommand($cmd) { 9 $this->_commands []= $cmd; 10 } 11 12 public function runCommand($name, $args) { 13 foreach($this->_commands as $cmd) { 14 if ($cmd->onCommand($name, $args)) return; 15 } 16 } 17 } 18 19 class UserCommand implements ICommand { 20 public function onCommand($name, $args) { 21 if ($name != 'addUser') return false; 22 echo("UserCommand handling 'addUser' "); 23 return true; 24 } 25 } 26 27 class MailCommand implements ICommand { 28 public function onCommand($name, $args) { 29 if ($name != 'mail') return false; 30 echo("MailCommand handling 'mail' "); 31 return true; 32 } 33 } 34 35 $cc = new CommandChain(); 36 $cc->addCommand(new UserCommand()); 37 $cc->addCommand(new MailCommand()); 38 $cc->runCommand('addUser', null); 39 $cc->runCommand('mail', null); 40 ?>

命令模式的优缺点:

优点:

1. 降低系统的耦合度

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

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

缺点:

使用命令模式可能会导致某些系统有过多的具体命令类。因为针对每一个命令都需要设计一个具体命令类,因此某些系统可能需要大量具体命令类,这将影响命令模式的使用。 

原文地址:https://www.cnblogs.com/dawuge/p/9400831.html