【设计模式】命令模式

概念

行为模式


类图


代码

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;
}
相关推荐
知守观10 小时前
设计模式实战:从真实老项目中看标准模板方法与工厂的落地
java·spring·设计模式
多弗朗皮卡丘21 小时前
C++特殊类设计
开发语言·c++·设计模式
Carl_奕然1 天前
【智能体】Loop 的四种设计模式之:Verification Loop(2026 最新版)
人工智能·python·设计模式
是2的10次方啊1 天前
设计模式与生活③:你的早晨,是一套模板
设计模式
.Hypocritical.2 天前
JUC + 三大设计模式(单例、工厂、代理)
设计模式·juc·1024程序员节
是2的10次方啊2 天前
设计模式与生活②:你只管点外卖,别管堡怎么做
设计模式
是2的10次方啊3 天前
设计模式与生活①:你的脸,为什么不能有第二个?
设计模式
高晶3 天前
ARM 嵌入式 Linux 命令系统 BusyBox 实战指南
linux·设计模式·程序员
高晶3 天前
语音合成与变声技术十大业务场景落地实战:从电商直播到规模化生产
设计模式·程序员
博风3 天前
19、设计模式应用举例:桥接模式:制作电视节目
设计模式·桥接模式