大话设计模式之命令模式

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

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

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

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

相关推荐
sg_knight14 小时前
适配器模式(Adapter)
python·设计模式·适配器模式·adapter
郝学胜-神的一滴17 小时前
Effective Modern C++ 条款40:深入理解 Atomic 与 Volatile 的多线程语义
开发语言·c++·学习·算法·设计模式·架构
九狼20 小时前
Riverpod 2.0 代码生成与依赖注入
flutter·设计模式·github
geovindu21 小时前
python: Visitor Pattern
python·设计模式·访问者模式
五阿哥永琪1 天前
常见设计模式简介
设计模式
资深web全栈开发1 天前
CQS - 命令查询分离:驯服副作用
设计模式
geovindu2 天前
python: Template Method Pattern
开发语言·python·设计模式·模板方法模式
HY小海2 天前
【Unity游戏创作】常见的设计模式
unity·设计模式·c#·游戏程序
Yongqiang Cheng2 天前
设计模式:C++ 模板方法模式 (Template Method in C++)
设计模式·template method·c++ 模板方法模式
我爱cope2 天前
【从0开始学设计模式-3| 工厂模式】
设计模式