【设计模式】命令模式

概念

行为模式


类图


代码

cpp 复制代码
#include <iostream>
#include <stack>

using namespace std;

class Editor {
public:
    string GetSelection() { return text; };
    void DeleteSelection() { text = ""; };
    void ReplaceSelection(const string& t) { text = t; };

private:
    string text;
};

class Application;
class Command {
public:
    Command(Application* app, Editor* editor) {
        this->app = app;
        this->editor = editor;
    }

    void SaveBackup() {
        backup = editor->GetSelection();
    }

    void Undo() {
        editor->ReplaceSelection(backup);
    }

    virtual bool Execute() = 0;

protected:
    Application* app;
    Editor* editor;
    string backup;
};

class CopyCommand : public Command {
public:
    bool Execute() override {
        SaveBackup();
        // app->clipboard = editor->GetSelection();
        return false;
    }
};

class CutCommand : public Command {
public:
    bool Execute() override {
        SaveBackup();
        // app->clipboard = editor->GetSelection();
        editor->DeleteSelection();
        return true;
    }
};

class PasteCommand : public Command {
public:
    bool Execute() override {
        SaveBackup();
        // editor->ReplaceSelection(app->clipboard);
        return true;
    }
};

class UndoCommand : public Command {
public:
    bool Execute() override {
        // app->Undo();
        return false;
    }
};

class CommandHistory {
public:
    void Push(Command* cmd) {
        history.push(cmd);
    }

    Command* Pop() {
        auto cmd = history.top();
        history.pop();
        return cmd;
    }

private:
    stack<Command*> history;
};

class Application {
    // omit cause one cpp file
};

int main(int argc, char *argv[]) {
    cout << "Command pattern needs to be complemented." << endl;
    cout << "One cpp file cannot satisfy." << endl;

    return 0;
}
相关推荐
HL_风神8 小时前
设计原则之迪米特
c++·学习·设计模式
HL_风神8 小时前
设计原则之合成复用
c++·学习·设计模式
Aeside111 小时前
揭秘 Nginx 百万并发基石:Reactor 架构与 Epoll 底层原理
后端·设计模式
帅气的你12 小时前
从零封装一个通用的 API 接口返回类:统一前后端交互格式
java·设计模式
阿里巴巴淘系技术团队官网博客12 小时前
GenAI输出内容控制的5种设计模式
设计模式
沛沛老爹14 小时前
Skills高级设计模式(一):向导式工作流与模板生成
java·人工智能·设计模式·prompt·aigc·agent·web转型
__万波__16 小时前
二十三种设计模式(二十二)--策略模式
java·设计模式·策略模式
Overt0p17 小时前
抽奖系统(6)
java·spring boot·redis·设计模式·rabbitmq·状态模式
__万波__17 小时前
二十三种设计模式(二十三)--责任链模式
java·设计模式·责任链模式
帅次18 小时前
系统设计方法论全解:原则、模型与用户体验核心要义
设计模式·流程图·软件工程·软件构建·需求分析·设计规范·规格说明书