【设计模式】命令模式

概念

行为模式


类图


代码

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;
}
相关推荐
崎岖Qiu9 小时前
【设计模式笔记17】:单例模式1-模式分析
java·笔记·单例模式·设计模式
安冬的码畜日常14 小时前
【JUnit实战3_27】第十六章:用 JUnit 测试 Spring 应用:通过实战案例深入理解 IoC 原理
spring·观察者模式·设计模式·单元测试·ioc·依赖注入·junit5
她说彩礼65万16 小时前
C#设计模式 单例模式实现方式
单例模式·设计模式·c#
安冬的码畜日常19 小时前
【JUnit实战3_28】第十七章:用 JUnit 5 实测 SpringBoot 项目
spring boot·功能测试·测试工具·设计模式·单元测试·junit5
围巾哥萧尘20 小时前
TRAE Agent 歌曲创作助手构建与使用教程🧣
设计模式
superman超哥20 小时前
仓颉语言中流式I/O的设计模式深度剖析
开发语言·后端·设计模式·仓颉
m0_7482480221 小时前
Spring设计模式刨根问底
java·spring·设计模式
不要额外加糖1 天前
tql,寥寥几行,实现无队列无感刷新
前端·javascript·设计模式
ACGkaka_1 天前
设计模式学习(十二)状态模式
学习·设计模式·状态模式
乐悠小码1 天前
Java设计模式精讲---01工厂方法模式
java·设计模式·工厂方法模式