7. 命令模式

目录

一、解决的问题

  • 将行为请求者与行为实现者解耦,当用户发出命令后,无需关注谁来执行命令。
  • 将命令的发出者和命令的执行者完全隔离开。

二、设计类图

  • Client:创建具体的命令对象,并且设置命令对象的接收者
  • Invoker:命令传递者,要求命令对象执行请求
  • Command:定义命令的接口
  • ConcreteCommand:命令接口实现对象
  • Receiver:命令接收并执行

三、代码实现

3.1 设计类图

  • 以电视机遥控器作为背景进行,类图如下

3.2 代码实现

cpp 复制代码
#include <iostream>

class TV
{
private:
    int currentChannel = 0;

public:
    void changeChannel(int channel)
    {
        this->currentChannel = channel;
    }

    void turnOff()
    {
        std::cout << "TV is off." << std::endl;
    }

    void turnOn()
    {
        std::cout << "TV is on." << std::endl;
    }
};

class Command
{
public:
    virtual void execute() = 0;
};

class CommandOn : public Command
{
private:
    TV* myTV;
public:
    CommandOn(TV* tv)
    {
        myTV = tv;
    }

    void execute()
    {
        myTV->turnOn();
    }
};

class CommandOff : public Command
{
private:
    TV* myTV;
public:
    CommandOff(TV* tv)
    {
        myTV = tv;
    }

    void execute()
    {
        myTV->turnOff();
    }
};

class CommandChange : public Command
{
private:
    TV* myTV;
    int channel;
public:
    CommandChange(TV* tv, int channel)
    {
        myTV = tv;
        this->channel = channel;
    }

    void execute()
    {
        std::cout << "Switch Channel to " << channel << std::endl;
        myTV->changeChannel(channel);
    }
};

class Control
{
private:
    Command* changChannel;
    Command* offCommand;
    Command* onCommand;

public:
    Control(Command* changChannel, Command* off, Command* on)
    {
        this->changChannel = changChannel;
        this->offCommand = off;
        this->onCommand = on;
    }

    void changeChannel()
    {
        changChannel->execute();
    }
    
    void turnOff()
    {
        offCommand->execute();
    }

    void turnOn()
    {
        onCommand->execute();
    }
};

int main()
{
    TV* mytv = new TV();
    Command* on = new CommandOn(mytv);
    Command* off = new CommandOff(mytv);
    Command* channel = new CommandChange(mytv, 3);

    Control* control = new Control(channel, off, on);

    control->turnOn();
    control->changeChannel();
    control->turnOff();
    return 0;
}

四、扩展

  • 定义一个3对控制器的按钮
  • 分别控制客厅灯、厨房灯和车库门的开关操作
  • 类图如下
  • 运行结果
  • 代码部分请参阅 https://gitee.com/piglittle/design_patterns中的 Head_First_Design_Partterns解决方案下的 command_pattern项目
相关推荐
IT小白架构师之路9 小时前
常用设计模式系列(十八)-责任链模式
设计模式·责任链模式
源代码•宸17 小时前
深入浅出设计模式——行为型模式之观察者模式 Observer
开发语言·c++·经验分享·观察者模式·设计模式·raii
快起来别睡了19 小时前
前端设计模式:让代码更优雅的“万能钥匙”
前端·设计模式
使二颗心免于哀伤1 天前
《设计模式之禅》笔记摘录 - 14.组合模式
笔记·设计模式·组合模式
原则猫2 天前
装饰器工程运用-埋点
设计模式
愿天堂没有C++2 天前
剑指offer第2版——面试题2:实现单例
c++·设计模式·面试
静谧之心2 天前
分层架构下的跨层通信:接口抽象如何解决反向调用
java·开发语言·设计模式·架构·golang·k8s·解耦
用户84913717547163 天前
JustAuth实战系列(第5期):建造者模式进阶 - AuthRequestBuilder设计解析
java·设计模式·架构
只因在人海中多看了你一眼3 天前
B.10.01.5-电商系统的设计模式应用实战
设计模式
希望_睿智3 天前
实战设计模式之代理模式
c++·设计模式·架构