设计模式 命令模式

82 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。 image.png

介绍

shiyanlou:在软件设计中,我们有时需要向某些对象发送请求(命令),但是对于请求(命令)发送者来说,并不知道请求(命令)的接收者是谁,它只需要发送命令即可;对于请求(命令)的接受者来说,他也并不知道给他发送请求(命令)的是谁,它只需要在有请求(命令)时执行自己的 action 即可。具体的请求(命令)发送者和接受者,我们就可以根据自己的需求自由组合。使得请求发送者与请求接收者消除彼此之间的耦合,让对象之间的调用关系更加灵活。主要特点就是将一个请求封装为一个对象,从而使我们可用不同的请求对客户进行参数化;对请求排队或者记录请求日志,以及支持可撤销的操作。命令模式是一种对象行为型模式,其别名为动作(Action)模式或事务(Transaction)模式。

角色

角色说明
Command抽象命令类
ConcreteCommand具体命令类
Invoker调用者
Receiver接收者
Client客户类

角色示例

类名担任角色说明
CommandCommand抽象命令类
StartCommandConcreteCommand启动命令类
StopCommandConcreteCommand停止命令类
RemoteControllerInvoker遥控器类
AirConditionerReceiver空调类
UserClient用户类

UML类图

image.png

代码

<?php 
class AirConditioner
{
    public function start()
    {
        return "启动空调".PHP_EOL;
    }

    public function stop()
    {
        return "关闭空调".PHP_EOL;
    }
}

abstract class Command
{
    protected $airConditioner;
    function __construct(AirConditioner $airConditioner)
    {
        $this->airConditioner = $airConditioner;
    }
    abstract public function execute();
}

class StartCommand extends Command
{
    function __construct(AirConditioner $airConditioner)
    {
        parent::__construct($airConditioner);
    }

    public function execute()
    {
        return $this->airConditioner->start();
    }
}

class StopCommand extends Command
{
    function __construct(AirConditioner $airConditioner)
    {
        parent::__construct($airConditioner);
    }

    public function execute()
    {
        return $this->airConditioner->stop();
    }
}

class RemoteController
{
    protected $command;
    function __construct(Command $command)
    {
        $this->command = $command;
    }

    public function control()
    {
        return $this->command->execute();
    }
}

class User
{
    public function setCommand(Command $command){
        return (new remoteController($command))->control();
    }
}

$user = new User();
$airConditioner = new AirConditioner();

$startCommand = new StartCommand($airConditioner);
echo $user->setCommand($startCommand);

$stopCommand = new StopCommand($airConditioner);
echo $user->setCommand($stopCommand);

创建 Command.php,内容如上。

执行

$ php Command.php
启动空调
关闭空调