php设计模式(十九)命令模式

命令模式就和名字一样;
比较适合执行命令的场景;
命令发送者只管调用具体命令类中的 execute() 方法;
然后在具体命令类中设定命令接收者;
可以消除命令发送者和命令接受者之间的耦合;
并且可以方便的扩展新命令;

结构

CommandInterface:命令抽象类;一般会暴露一个 execute 方法;
Command:具体的命令类;设定接收者;
Invoker:命令发送者;用于调用命令;
Receiver: 命令接收者;负责执行操作;

示例

CommandInterface.php

<?php

namespace Baijunyao\DesignPatterns\Command;

/**
 * Interface CommandInterface
 *
 * @package Baijunyao\DesignPatterns\Command
 */
interface CommandInterface
{

    /**
     * @return mixed
     */
    public function execute();
}

具体的命令类;
Command.php

<?php

namespace Baijunyao\DesignPatterns\Command;

/**
 * 具体命令类
 *
 * @package Baijunyao\DesignPatterns\Command
 */
class Command implements CommandInterface
{
    /**
     * @var \Baijunyao\DesignPatterns\Command\Receiver
     */
    protected $receiver;

    /**
     * Command constructor.
     *
     * @param \Baijunyao\DesignPatterns\Command\Receiver $receiver
     */
    public function __construct(Receiver $receiver)
    {
        $this->receiver = $receiver;
    }

    /**
     * @return mixed|void
     */
    public function execute()
    {
        $this->receiver->action();
    }
}

命令发送者

<?php

namespace Baijunyao\DesignPatterns\Command;

/**
 * 命令发送者
 *
 * @package Baijunyao\DesignPatterns\Command
 */
class Invoker
{
    /**
     * @var
     */
    protected $command;

    /**
     * @param \Baijunyao\DesignPatterns\Command\Command $command
     */
    public function setCommand(Command $command)
    {
        $this->command = $command;
    }

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

命令接受者

<?php

namespace Baijunyao\DesignPatterns\Command;

/**
 * 命令接收者
 *
 * @package Baijunyao\DesignPatterns\Command
 */
class Receiver
{
    /**
     * 执行操作
     */
    public function action()
    {
        echo '执行操作';
    }
}

运行;
index.php

<?php

namespace Baijunyao\DesignPatterns\Command;

require __DIR__.'/../vendor/autoload.php';

/**
 * 客户端
 *
 * Class Client
 * @package Baijunyao\DesignPatterns\Command
 */
class Client
{
    /**
     * 运行
     */
    public function run()
    {
        // 命令行类设定接受者
        $receiver = new Receiver();
        $command = new Command($receiver);

        // 命令接受者调用命令
        $invoker = new Invoker();
        $invoker->setCommand($command);
        $invoker->run();
    }
}

$client = new Client();
$client->run();

但是正如代码所示;
本来只是要执行一个方法;
却分成了3个类显的略微繁琐;


github示例:https://github.com/baijunyao/design-patterns/tree/master/Command

白俊遥博客
请先登录后发表评论
  • 最新评论
  • 总共1条评论
白俊遥博客

关元:终于更新了,挺喜欢这个系列的

2018-11-19 11:05:54 回复