设计模式-命令模式
作者:edwin
日期:2020-03-08 17:13:56
所属分类:后端 - php

将“请求”封装成对象,以便对命令进行管理。使用不同的请求、队列或者日志来参数化其他对象

角色:

  1、命令(Command):为所有命令声明了一个接口。调用命令对象的 execute()方法,就可以让接收者进行相关的操作。这个接口也具备一个 undo() 方法。
 2、具体命令(ConcreteCommand):实现命令接口,定义了动作和接收者之间的绑定关系。调用者只要调用 execute() 就可以发出请求,然后由 ConcreteCommand 调用接收者的一个或多个动作。
 3、请求者(Invoker):持有一个命令对象,有一个行动方法,在某个时间点调用命令对象的 execute() 方法,将请求付诸实行。
 4、接收者(Receiver):接收者知道如何进行必要的动作,实现这个请求。任何类都可以当接收者。
 5、客户端(Client):创建一个具体命令(ConcreteCommand)对象并确定其接收者,包括把其他角色串连在一起。

实现代码

class ConcreteCommand implements Command
{
    private $_receiver;
    public function __construct($receiver)
    {
        $this->_receiver = $receiver;
    }

    public function execute()
    {
        $this->_receiver->action();
    }
}

class ConcreteCommand1 implements Command
{
    private $_receiver;
    public function __construct($receiver)
    {
        $this->_receiver = $receiver;
    }

    public function execute()
    {
        $this->_receiver->action1();
    }
}

class ConcreteCommand2 implements Command
{
    private $_receiver;
    public function __construct($receiver)
    {
        $this->_receiver = $receiver;
    }

    public function execute()
    {
        $this->_receiver->action();
        $this->_receiver->action1();
    }
}

class Receiver
{
    private $_name = null;

    public function __construct($name)
    {
        $this->_name = $name;
    }

    public function action()
    {
        echo $this->_name . " action";
    }

    public function action1()
    {
        echo $this->_name . " action1";
    }
}

interface Command
{
    public function execute();
}

class Invoker
{
    private $_command = array();
    public function setCommand($command)
    {
        $this->_command[] = $command;
    }

    public function executeCommand()
    {
        foreach ($this->_command as $command) {
            $command->execute();
        }
    }

    public function removeCommand($command)
    {
        $key = array_search($command, $this->_command);
        if ($key !== false) {
            unset($this->_command[$key]);
        }
    }
}

$objRecevier = new Receiver("No.1");
$objRecevier1 = new Receiver("No.2");
$objRecevier2 = new Receiver("No.3");

$objCommand = new ConcreteCommand($objRecevier);
$objCommand1 = new ConcreteCommand1($objRecevier);
$objCommand2 = new ConcreteCommand($objRecevier1);
$objCommand3 = new ConcreteCommand1($objRecevier1);
$objCommand4 = new ConcreteCommand2($objRecevier2); // 使用 Recevier的两个方法

$objInvoker = new Invoker();
$objInvoker->setCommand($objCommand);
$objInvoker->setCommand($objCommand1);
$objInvoker->executeCommand();
$objInvoker->removeCommand($objCommand1);
$objInvoker->executeCommand();

$objInvoker->setCommand($objCommand2);
$objInvoker->setCommand($objCommand3);
$objInvoker->setCommand($objCommand4);
$objInvoker->executeCommand();

评论

全部评论 / 0