PHP 设计模式系列 -- 命令模式(Command)

原创
2016-06-23 13:20:17 667浏览

1、模式定义

命令模式(Command)将请求封装成对象,从而使你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤消的操作。这么说很抽象,我们举个例子:

假设我们有一个调用者类 Invoker 和一个接收调用请求的类 Receiver,在两者之间我们使用命令类 Command 的 execute 方法来托管请求调用方法,这样,调用者 Invoker 只知道调用命令类的 execute 方法来处理客户端请求,从而实现接收者 Receiver 与调用者 Invoker 的解耦。

Laravel 中的Artisan 命令就使用了命令模式。

2、UML类图

3、示例代码

CommandInterface.php

HelloCommand.php

output = $console;    }    /**     * 执行并输出 "Hello World"     */    public function execute()    {        // 没有Receiver的时候完全通过命令类来实现功能        $this->output->write('Hello World');    }}

Receiver.php

Invoker.php

command = $cmd;    }    /**     * 执行命令     */    public function run()    {        $this->command->execute();    }}

4、测试代码

Tests/CommandTest.php

invoker = new Invoker();        $this->receiver = new Receiver();    }    public function testInvocation()    {        $this->invoker->setCommand(new HelloCommand($this->receiver));        $this->expectOutputString('Hello World');        $this->invoker->run();    }}

5、总结

命令模式就是将一组对象的相似行为,进行了抽象,将调用者与被调用者之间进行解耦,提高了应用的灵活性。命令模式将调用的目标对象的一些异构性给封装起来,通过统一的方式来为调用者提供服务。

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。