zoukankan      html  css  js  c++  java
  • 命令模式

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

    在软件设计中,我们经常需要向某些对象发送请求,但是并不知道请求的接收者是谁,也不知道被请求的操作是哪个,我们只需在程序运行时指定具体的请求接收者即可,此时,可以使用命令模式来进行设计,使得请求发送者与请求接收者消除彼此之间的耦合,让对象之间的调用关系更加灵活。
    命令模式可以对发送者和接收者完全解耦,发送者与接收者之间没有直接引用关系,发送请求的对象只需要知道如何发送请求,而不必知道如何完成请求。这就是命令模式的模式动机。

    命令模式包含如下角色:
      Command: 抽象命令类
      ConcreteCommand: 具体命令类
      Invoker: 调用者
      Receiver: 接收者
      Client:客户类

    interface Command{
        function execute();
    }
    //具体命令角色AttackCommand,指定接受者执行攻击命令
    class AttackCommand implements Command{
        private $receiver;
        function __construct(Receiver $receiver){
            $this->receiver = $receiver;
        }
        function execute(){
            $this->receiver->attackAction();
        }
    }
    //具体命令角色DefenseCommand,指定接受者执行防御命令
    class DefenseCommand implements Command{
        private $receiver;
        function __construct(Receiver $receiver){
            $this->receiver = $receiver;
        }
        function execute(){
            $this->receiver->defenseAction();
        }
    }
    //接受者,执行具体命令角色的命令
    class Receiver{
        private $name;
        function __construct($name){
            $this->name = $name;
        }
        function attackAction(){
            echo $this->name."执行了攻击命令";
        }
        function defenseAction(){
            echo $this->name."执行了防御命令";
        }
    }
    //请求者,请求具体命令的执行
    class Invoker{
        private $concreteCommand;
        function __construct($concreteCommand){
            $this->concreteCommand = $concreteCommand;
        }
        function executeCommand(){
            $this->concreteCommand->execute();
        }
    }
    
    //客户端角色
    class Client{
        function __construct(){
            $receiverZhao = new Receiver("赵日天");
            $attackCommand = new AttackCommand($receiverZhao);
            $attackInvoker = new Invoker($attackCommand);
            $attackInvoker->executeCommand();
    
            $receiverYe = new Receiver("叶良辰");
            $defenseCommand = new DefenseCommand($receiverYe);
            $defenseInvoker = new Invoker($defenseCommand);
            $defenseInvoker->executeCommand();
        }
    }
    
  • 相关阅读:
    wrap添加及去除外层dom的方法
    闭包作用域探究小例
    测试模型之W模型(脑图)
    软件测试模型之前置模型(脑图)
    软件测试模型之H模型(脑图)
    软件测试基础(脑图)
    测试模型之V模型(脑图)
    一个点型的rsyncd.conf内容
    rsync同步时报name lookup failed for name or service not known错误的解决方法
    ubuntu下的eclipse 3.3初用aptana报SWT错误
  • 原文地址:https://www.cnblogs.com/paulversion/p/8482544.html
Copyright © 2011-2022 走看看