【设计模式】命令模式

概念

行为模式


类图


代码

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;
}
相关推荐
J_liaty3 小时前
23种设计模式一代理模式
设计模式·代理模式
苏渡苇9 小时前
优雅应对异常,从“try-catch堆砌”到“设计驱动”
java·后端·设计模式·学习方法·责任链模式
短剑重铸之日10 小时前
《设计模式》第十一篇:总结
java·后端·设计模式·总结
feasibility.10 小时前
AI 编程助手进阶指南:从 Claude Code 到 OpenCode 的工程化经验总结
人工智能·经验分享·设计模式·自动化·agi·skills·opencode
BD_Marathon11 小时前
七大设计原则介绍
设计模式
YigAin13 小时前
Unity23种设计模式之 享元模式
设计模式·享元模式
不绝1911 天前
UGUI相关——基础篇
命令模式
范纹杉想快点毕业1 天前
实战级ZYNQ中断状态机FIFO设计
java·开发语言·驱动开发·设计模式·架构·mfc
茂桑1 天前
DDD领域驱动设计-基础设施层
设计模式·架构
小温冲冲1 天前
通俗且全面精讲工厂设计模式
设计模式