【设计模式】命令模式

概念

行为模式


类图


代码

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;
}
相关推荐
ZHE|张恒1 天前
设计模式(十二)代理模式 — 用代理控制访问,实现延迟加载、权限控制等功能
设计模式·代理模式
SakuraOnTheWay1 天前
《深入设计模式》学习(1)—— 深入理解OOP中的6种对象关系
设计模式
q***71851 天前
Java进阶-SpringCloud设计模式-工厂模式的设计与详解
java·spring cloud·设计模式
白衣鸽子1 天前
告别参数地狱:业务代码中自定义Context的最佳实践
后端·设计模式·代码规范
帅中的小灰灰2 天前
C++编程建造器设计模式
java·c++·设计模式
ZHE|张恒2 天前
设计模式(十)外观模式 — 提供统一入口,简化复杂系统的使用
设计模式·外观模式
howcode2 天前
女友去玩,竟带回一道 “虐哭程序员” 的难题
后端·设计模式·程序员
apigfly3 天前
深入Android系统(十三)Android的窗口系统
android·设计模式·源码
y***54883 天前
Java设计模式之观察者模式
观察者模式·设计模式
明洞日记3 天前
【设计模式手册010】组合模式 - 树形结构的优雅处理
java·设计模式·组合模式