【设计模式】命令模式

概念

行为模式


类图


代码

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;
}
相关推荐
workflower15 小时前
例二:某汽车制造企业深度融合AI智能体,构建园区网络的智能运维体系
人工智能·机器学习·设计模式·机器人·云计算·汽车·制造
ly768916 小时前
Java 设计模式详解:从原则到 23 种经典模式
java·开发语言·设计模式
AI人工智能+电脑小能手19 小时前
大白话说Java设计模式-14-适配器模式(业务实战篇)
java·设计模式·适配器模式·系统兼容·多渠道对接
略略略咯咯1 天前
(总结)设计模式
设计模式
Cosolar2 天前
DeepSeek Harness 理解 Harness 的设计哲学 - 可组合的插件运行时
人工智能·设计模式·架构
Nebula_g2 天前
JavaSE基础语法:特殊类(特殊情景下的设计模式)
java·开发语言·设计模式
George_Ye2 天前
同一本书,一人一份:我如何设计 AI 个性化扫书报告
设计模式
莫得感情 o3 天前
设计模式 22 · 三个冷门模式:中介者、访问者、解释器
java·设计模式
AI人工智能+电脑小能手4 天前
大白话说Java设计模式-08-建造者模式(业务实战篇)
java·设计模式·建造者模式·架构设计·对象构建
AustinXu4 天前
从 Claude Code 到 Claude Tag,Harness Engineering 走到了组织这一层
设计模式·团队管理