命令模式就是将一组对象的相似行为,进行了抽象,将调用者与被调用者之间进行解耦,提高了应用的灵活性。命令模式将调用的目标对象的一些异构性给封装起来,通过统一的方式来为调用者提供服务。
CommandInterface.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| <?php
namespace DesignPatterns\Behavioral\Command;
interface CommandInterface {
public function execute(); }
|
HelloCommand.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| <?php
namespace DesignPatterns\Behavioral\Command;
class HelloCommand implements CommandInterface {
protected $output;
public function __construct(Receiver $console) { $this->output = $console; }
public function execute() { $this->output->write('Hello World'); } }
|
Receiver.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| <?php
namespace DesignPatterns\Behavioral\Command;
class Receiver {
public function write($str) { echo $str; } }
|
Invoker.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| <?php
namespace DesignPatterns\Behavioral\Command;
class Invoker {
protected $command;
public function setCommand(CommandInterface $cmd) { $this->command = $cmd; }
public function run() { $this->command->execute(); } }
|
测试代码 Tests/CommandTest.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| <?php
namespace DesignPatterns\Behavioral\Command\Tests;
use DesignPatterns\Behavioral\Command\Invoker; use DesignPatterns\Behavioral\Command\Receiver; use DesignPatterns\Behavioral\Command\HelloCommand;
/** * CommandTest在命令模式中扮演客户端角色 */ class CommandTest extends \PHPUnit_Framework_TestCase {
/** * @var Invoker */ protected $invoker;
/** * @var Receiver */ protected $receiver;
protected function setUp() { $this->invoker = new Invoker(); $this->receiver = new Receiver(); }
public function testInvocation() { $this->invoker->setCommand(new HelloCommand($this->receiver)); $this->expectOutputString('Hello World'); $this->invoker->run(); } }
|