云里雾里命令模式

还没搞明白,先把可以执行的代码扔上来

源代码https://github.com/domnikl/DesignPatternsPHP/blob/master/Behavioral/Command/README.rst

我做了一点调整,为了自己本地跑通。

 

代码结构

云里雾里命令模式_第1张图片

Command.php

Receiver.php

enableDate) {
            $str .= ' [' . date('Y-m-d') . ']';
        }
        echo "Receiver->write 
"; $this->output[] = $str; } public function getOutput() { echo "Receiver->getOutput
"; return join("\n", $this->output); } /** * Enable receiver to display message date */ public function enableDate() { echo "Receiver->enableDate
"; $this->enableDate = true; } /** * Disable receiver to display message date */ public function disableDate() { echo "Receiver->disableDate
"; $this->enableDate = false; } }

Invoker.php

setCommand 
"; $this->command = $cmd; } /** * executes the command; the invoker is the same whatever is the command */ public function run() { echo "Invoker->run
"; $this->command->execute(); } }

UndoableCommand.php

AddMessageDateCommand.php

__construct 
"; $this->output = $console; } /** * Execute and make receiver to enable displaying messages date. */ public function execute() { echo "AddMessageDateCommand->execute
"; // sometimes, there is no receiver and this is the command which // does all the work $this->output->enableDate(); } /** * Undo the command and make receiver to disable displaying messages date. */ public function undo() { echo "AddMessageDateCommand->undo
"; // sometimes, there is no receiver and this is the command which // does all the work $this->output->disableDate(); } }

HelloCommand.php

__construct 
"; $this->output = $console; } /** * execute and output "Hello World". */ public function execute() { echo "HelloCommand->execute
"; // sometimes, there is no receiver and this is the command which does all the work $this->output->write('Hello World'); } }

 

test.php

setCommand(new HelloCommand($receiver));
$invoker->run();
echo $receiver->getOutput();

输出结果

HelloCommand->__construct 
Invoker->setCommand 
Invoker->run 
HelloCommand->execute 
Receiver->write 
Receiver->getOutput 
Hello World

 

你可能感兴趣的:(php,设计模式)