<?php
//抽象命令接口
interface Command
{
//命令执行
public function execute();
}
//宏命令(命令的组合)
//宏命令接口
interface MacroCommand extends Command
{
//宏命令聚集管理方法,可以删除一个命令
public function remove(Command $command);
//宏命令聚集管理方法,可以添加一个命令
public function add(Command $command);
}
//命令的实现
//复制命令
class CopyCommand implements Command
{
private $receiver;
public function __construct(Receiver $receiver)
{
$this->receiver = $receiver;
}
public function execute()
{
$this->receiver->copy();
}
}
//粘贴命令
class PasteCommand implements Command
{
private $receiver;
public function __construct(Receiver $receiver)
{
$this->receiver = $receiver;
}
public function execute()
{
$this->receiver->paste();
}
}
//命令接收者执行命令
class Receiver
{
private $name;
public function __construct($name)
{
$this->name = $name;
}
public function copy()
{
echo $this->name . '执行copy命令';
}
public function paste()
{
echo $this->name . '执行paste命令';
}
}
//命令请求者,用于发送请求
class Invoker
{
private $command;
public function __construct(Command $command)
{
$this->command = $command;
}
public function action()
{
$this->command->execute();
}
}
//实现宏命令
class TestMacroCommand implements MacroCommand
{
private $commands;
public function __construct()
{
$this->commands = [];
}
//宏命令聚集管理方法,可以删除一个命令
public function remove(Command $command)
{
$index = array_search($command, $this->commands);
if ($index === false) {
return false;
} else {
unset($this->commands[$index]);
return true;
}
}
//宏命令聚集管理方法,可以添加一个命令
public function add(Command $command)
{
return array_push($this->commands, $command);
}
public function execute()
{
if (!is_array($this->commands)) {
return false;
} else {
foreach ($this->commands as $command) {
//通知改变
$command->execute();
}
}
return true;
}
}
//客户端
$receiver = new Receiver('gd');
$copy_command = new CopyCommand($receiver);
$paste_command = new PasteCommand($receiver);
//添加命令到宏命令
$macro_command = new TestMacroCommand();
$macro_command->add($copy_command);
$macro_command->add($paste_command);
$invoker = new Invoker($macro_command);
$invoker->action();