【设计模式】命令模式

概念

行为模式


类图


代码

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;
}
相关推荐
ZJPRENO6 小时前
吃透软件开发六大设计原则,告别烂代码
设计模式
咖啡八杯6 小时前
GoF设计模式——命令模式
java·设计模式·架构
花椒技术1 天前
HJPusher / HJPlayer SDK 实践:我们为什么把直播推播链路拆成一套可复用能力
设计模式·harmonyos·直播
艺艺生辉1 天前
迭代器模式-"我也想被增强for循环"
设计模式
咖啡八杯3 天前
GoF设计模式——策略模式
java·后端·spring·设计模式
槑有老呆4 天前
别再手搓 Prompt 了,那个叫"手动挡循环"
设计模式
用户6919026813395 天前
Vibe Coding 开发项目的基本范式
人工智能·设计模式·代码规范
怕浪猫6 天前
领域特定语言(Domain-Specific Language, DSL)
设计模式·程序员·架构