• 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. 可以比较容易地设计一个组合命令

    缺点:

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

  • 相关阅读:
    本博客完美的支持移动端
    vue监听滚动事件,元素顶部吸附实现
    提高java反射速度的方法method.setAccessible(true)
    居家必备技能之检测电表是否虚高
    家用无线网络故障排查记录
    java 泛型类的继承关系和转型问题
    Office2019 相关激活秘钥
    IDEA记坑之移动项目文件之后,import 找不到文件以及出现Cannot access的问题
    Idea 可用激活方式
    MySQL 合并查询,以map或对象的形式返回
  • 原文地址:https://www.cnblogs.com/dawuge/p/9400831.html
Copyright © 2020-2023  润新知