【设计模式】命令模式

概念

行为模式


类图


代码

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;
}
相关推荐
青草地溪水旁2 小时前
设计模式(C++)详解——命令模式(1)
c++·设计模式·命令模式
青草地溪水旁2 小时前
设计模式(C++)详解——命令模式(2)
c++·设计模式·命令模式
new_daimond2 小时前
设计模式-原型模式详解
设计模式·原型模式
星星点点洲3 小时前
【Golang】数据设计模式
开发语言·设计模式·golang
步行cgn3 小时前
责任链设计模式详解
设计模式
青草地溪水旁4 小时前
设计模式(C++)详解——职责链模式 (Chain of Responsibility)(2)
c++·设计模式·责任链模式
青草地溪水旁4 小时前
设计模式(C++)详解——职责链模式 (Chain of Responsibility)(1)
c++·设计模式·责任链模式
phdsky4 小时前
【设计模式】责任链模式
设计模式·责任链模式
yujkss4 小时前
23种设计模式之【责任链模式】-核心原理与 Java 实践
java·设计模式·责任链模式