大话设计模式之命令模式

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

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

  • 命令(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() 函数中,我们创建了具体命令对象,
并将它们添加到调用者中,最后执行了命令。
*/

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

相关推荐
火车叨位去19499 小时前
软件设计模式(tyutJAVA 状态模式实验)
设计模式·状态模式
喝茶与编码18 小时前
工厂模式+抽象类 实战指南(基于文档导出业务)
设计模式
昨天的猫21 小时前
原来项目中的观察者模式是这样玩的
后端·设计模式
2301_795167201 天前
玩转Rust高级应用 如何进行面向对象设计模式的实现,实现状态模式
设计模式·rust·状态模式
星夜泊客1 天前
Unity 游戏开发中的防御性编程与空值处理实践
unity·设计模式·游戏引擎
Adellle1 天前
设计模式的介绍
设计模式
达斯维达的大眼睛1 天前
设计模式-单列模式
设计模式·cpp
Javatutouhouduan1 天前
记一次redis主从切换导致的数据丢失与陷入只读状态故障
java·redis·设计模式·java面试·高可用·java后端·java程序员
数据知道2 天前
Go语言设计模式:抽象工厂模式详解
设计模式·golang·抽象工厂模式·go语言
数据知道2 天前
Go语言设计模式:组合模式详解
设计模式·golang·组合模式·go语言