class Invoker
{
public $command;
public function __construct($command)
{
$this->command = $command;
}
public function exec()
{
$this->command->execute();
}
}
abstract class Command
{
protected $receiver;
public function __construct(Receiver $receiver)
{
$this->receiver = $receiver;
}
abstract public function execute();
}
class ConcreteCommand extends Command
{
public function execute()
{
$this->receiver->action();
}
}
接下来是命令,也就是我们的“菜单”。这个命令的作用是为了定义真正的执行者是谁。
class Receiver
{
public $name;
public function __construct($name)
{
$this->name = $name;
}
public function action()
{
echo $this->name . '命令执行了!', PHP_EOL;
}
}
接管者,也就是执行者,真正去执行命令的人。
// 准备执行者
$receiverA = new Receiver('A');
// 准备命令
$command = new ConcreteCommand($receiverA);
// 请求者
$invoker = new Invoker($command);
$invoker->exec();
<?php
class SendMsg
{
private $command = [];
public function setCommand(Command $command)
{
$this->command[] = $command;
}
public function send($msg)
{
foreach ($this->command as $command) {
$command->execute($msg);
}
}
}
abstract class Command
{
protected $receiver = [];
public function setReceiver($receiver)
{
$this->receiver[] = $receiver;
}
abstract public function execute($msg);
}
class SendAliYun extends Command
{
public function execute($msg)
{
foreach ($this->receiver as $receiver) {
$receiver->action($msg);
}
}
}
class SendJiGuang extends Command
{
public function execute($msg)
{
foreach ($this->receiver as $receiver) {
$receiver->action($msg);
}
}
}
class SendAliYunMsg
{
public function action($msg)
{
echo '【阿X云短信】发送:' . $msg, PHP_EOL;
}
}
class SendAliYunPush
{
public function action($msg)
{
echo '【阿X云推送】发送:' . $msg, PHP_EOL;
}
}
class SendJiGuangMsg
{
public function action($msg)
{
echo '【极X短信】发送:' . $msg, PHP_EOL;
}
}
class SendJiGuangPush
{
public function action($msg)
{
echo '【极X推送】发送:' . $msg, PHP_EOL;
}
}
$aliMsg = new SendAliYunMsg();
$aliPush = new SendAliYunPush();
$jgMsg = new SendJiGuangMsg();
$jgPush = new SendJiGuangPush();
$sendAliYun = new SendAliYun();
$sendAliYun->setReceiver($aliMsg);
$sendAliYun->setReceiver($aliPush);
$sendJiGuang = new SendJiGuang();
$sendAliYun->setReceiver($jgMsg);
$sendAliYun->setReceiver($jgPush);
$sendMsg = new SendMsg();
$sendMsg->setCommand($sendAliYun);
$sendMsg->setCommand($sendJiGuang);
$sendMsg->send('这次要搞个大活动,快来注册吧!!');