设计模式

设计模式 命令模式

2020-06-12  本文已影响0人  Yohann丶blog
WechatIMG39.jpeg

介绍

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

角色

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

角色示例

类名 担任角色 说明
Command Command 抽象命令类
StartCommand ConcreteCommand 启动命令类
StopCommand ConcreteCommand 停止命令类
RemoteController Invoker 遥控器类
AirConditioner Receiver 空调类
User Client 用户类

UML类图

命令模式.jpg

代码

<?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
启动空调
关闭空调
上一篇 下一篇

猜你喜欢

热点阅读