大话设计模式之命令模式

命令模式是一种行为型设计模式,它将请求或操作封装成一个对象,从而允许客户端参数化操作。这意味着客户端将一个请求封装为一个对象,这样可以将请求的参数化、队列化和记录日志,以及支持可撤销的操作。

命令模式主要由以下几个角色组成:

  • 命令(Command) :声明执行操作的接口,通常包含一个执行方法 execute()
  • 具体命令(Concrete Command):实现命令接口,具体定义了执行操作的方法。
  • 调用者(Invoker):负责调用命令对象执行请求的对象。
  • 接收者(Receiver):知道如何执行命令相关的操作,实现了实际的行为。
cpp 复制代码
#include <iostream>
#include <string>
#include <vector>

// 命令接口
class Command {
public:
    virtual ~Command() {}
    virtual void execute() = 0;
};

// 具体命令:打开文件命令
class OpenFileCommand : public Command {
private:
    std::string filename_;

public:
    OpenFileCommand(const std::string& filename) : filename_(filename) {}

    void execute() override {
        std::cout << "Opening file: " << filename_ << std::endl;
        // 实际打开文件的操作
    }
};

// 具体命令:关闭文件命令
class CloseFileCommand : public Command {
private:
    std::string filename_;

public:
    CloseFileCommand(const std::string& filename) : filename_(filename) {}

    void execute() override {
        std::cout << "Closing file: " << filename_ << std::endl;
        // 实际关闭文件的操作
    }
};

// 调用者
class Invoker {
private:
    std::vector<Command*> commands_;

public:
    void addCommand(Command* command) {
        commands_.push_back(command);
    }

    void executeCommands() {
        for (Command* command : commands_) {
            command->execute();
        }
    }
};

int main() {
    // 创建具体命令对象
    OpenFileCommand openFile("example.txt");
    CloseFileCommand closeFile("example.txt");

    // 创建调用者对象
    Invoker invoker;

    // 添加命令到调用者
    invoker.addCommand(&openFile);
    invoker.addCommand(&closeFile);

    // 执行命令
    invoker.executeCommands();

    return 0;
}

/*
在这个示例中,Command 是命令接口,声明了一个 execute() 方法用于执行命令。
OpenFileCommand 和 CloseFileCommand 是具体命令,分别表示打开文件和关闭文件的操作。
Invoker 是调用者,负责调用命令对象执行请求。在 main() 函数中,我们创建了具体命令对象,
并将它们添加到调用者中,最后执行了命令。
*/

觉得有帮助的话,打赏一下呗。。

相关推荐
青禾网络20 小时前
Web 前端如何接入 AI 音效生成:从零到可用的完整方案
人工智能·设计模式
ZJPRENO2 天前
吃透软件开发六大设计原则,告别烂代码
设计模式
咖啡八杯2 天前
GoF设计模式——命令模式
java·设计模式·架构
花椒技术3 天前
HJPusher / HJPlayer SDK 实践:我们为什么把直播推播链路拆成一套可复用能力
设计模式·harmonyos·直播
艺艺生辉3 天前
迭代器模式-"我也想被增强for循环"
设计模式
咖啡八杯4 天前
GoF设计模式——策略模式
java·后端·spring·设计模式
槑有老呆6 天前
别再手搓 Prompt 了,那个叫"手动挡循环"
设计模式
用户6919026813397 天前
Vibe Coding 开发项目的基本范式
人工智能·设计模式·代码规范
怕浪猫8 天前
领域特定语言(Domain-Specific Language, DSL)
设计模式·程序员·架构