如何用c++实现一个命令模式 轻松实现撤销和重做功能【设计模式】

命令模式通过将请求封装为对象实现参数化、排队、日志记录及撤销重做;C++中需定义含execute()和undo()的抽象基类,具体命令保存必要上下文,用双栈管理执行与撤销历史。

命令模式的核心是把“请求”封装成对象,这样就能参数化、排队、记录日志,还能支持撤销和重做。C++ 实现的关键在于:定义统一的命令接口、让每个具体操作实现该接口、用栈管理执行历史。

定义命令基类(支持撤销)

所有命令都继承自一个抽象基类,至少包含 execute()undo() 两个纯虚函数:

class Command {
public:
    virtual ~Command() = default;
    virtual void execute() = 0;
    virtual void undo() = 0;
};

注意:命令对象应保存执行所需的所有上下文(比如目标对象、原始值、参数),不能依赖外部状态——否则 undo 可能失败。

实现具体命令(以文本编辑为例)

比如“插入文字”命令需要记住插入位置和内容,以便撤销时删除它:

class TextEditor {
    std::string content;
    size_t cursor_pos = 0;
public:
    void insert(const std::string& text) {
        content.insert(cursor_pos, text);
        cursor_pos += text.length();
    }
    void deleteAt(size_t pos, size_t len) {
        content.erase(pos, len);
    }
    const std::string& getContent() const { return content; }
    size_t getCursor() const { return cursor_pos; }
};

class InsertCommand : public Command {
    TextEditor& editor;
    std::string text;
    size_t pos;
public:
    InsertCommand(TextEditor& e, const std::string& t)
        : editor(e), text(t), pos(e.getCursor()) {}

    void execute() override {
        editor.insert(text);
    }

    void undo() override {
        editor.deleteAt(pos, text.length());
    }
};

类似地,可以实现 DeleteCommand、ReplaceCommand 等,每个都保存足够信息用于反向操作。

用栈管理历史(支持撤销/重做)

维护两个栈:executed 存已执行的命令(用于 undo),undone 存刚撤销的命令(用于 redo):

  • 执行命令时:调用 cmd->execute(),然后 push 到 executed
  • 撤销时:pop executed,调用其 undo(),再 push 到 undone
  • 重做时:pop undone,调用 execute(),再 push 回 executed
class CommandInvoker {
    std::stack> executed;
    std::stack> undone;

public:
    void execute(std::unique_ptr cmd) {
        cmd->execute();
        executed.push(std::move(cmd));
        undone = {}; // 清空重做历史(常见策略,也可保留)
    }

    void undo() {
        if (!executed.empty()) {
            auto cmd = std::move(executed.top());
            executed.pop();
            cmd->undo();
            undone.push(std::move(cmd));
        }
    }

    void redo() {
        if (!undone.empty()) {
            auto cmd = std::move(undone.top());
            undone.pop();
            cmd->execute();
            executed.push(std::move(cmd));
        }
    }
};

组合与扩展技巧

复杂操作可由多个命令组成,用 CompositeCommand 统一管理:

  • 它也继承自 Command
  • execute() 顺序调用子命令的 execute()
  • undo() 倒序调用子命令的 undo()

另外,为避免内存泄漏,建议用 std::unique_ptr 管理命令对象;若需重复执行同一命令(如快捷键连按),确保命令是无状态或可重入的。