温馨提示×

c++命令模式如何实现撤销功能

c++
小樊
83
2024-11-23 19:51:34
栏目: 编程语言

在C++中,实现命令模式的撤销功能需要遵循以下步骤:

  1. 定义一个命令接口(Command):
class Command {
public:
    virtual ~Command() {}
    virtual void execute() = 0;
    virtual void undo() = 0;
};
  1. 为每个具体命令创建一个类,实现命令接口:
class ConcreteCommandA : public Command {
private:
    Receiver* receiver;

public:
    ConcreteCommandA(Receiver* receiver) : receiver(receiver) {}

    void execute() override {
        receiver->actionA();
    }

    void undo() override {
        receiver->undoActionA();
    }
};

class ConcreteCommandB : public Command {
private:
    Receiver* receiver;

public:
    ConcreteCommandB(Receiver* receiver) : receiver(receiver) {}

    void execute() override {
        receiver->actionB();
    }

    void undo() override {
        receiver->undoActionB();
    }
};
  1. 创建一个命令管理器(CommandManager),用于存储和管理命令对象,并提供执行和撤销功能:
#include <stack>

class CommandManager {
private:
    std::stack<Command*> commandStack;

public:
    void executeCommand(Command* command) {
        command->execute();
        commandStack.push(command);
    }

    void undoLastCommand() {
        if (!commandStack.empty()) {
            Command* command = commandStack.top();
            commandStack.pop();
            command->undo();
        }
    }
};
  1. 创建一个接收者(Receiver)类,包含实际要执行的操作和撤销操作:
class Receiver {
public:
    void actionA() {
        // 实际执行操作A
    }

    void undoActionA() {
        // 撤销操作A
    }

    void actionB() {
        // 实际执行操作B
    }

    void undoActionB() {
        // 撤销操作B
    }
};
  1. 在客户端代码中,使用命令模式执行和撤销操作:
int main() {
    Receiver receiver;
    CommandManager commandManager;

    Command* commandA = new ConcreteCommandA(&receiver);
    Command* commandB = new ConcreteCommandB(&receiver);

    commandManager.executeCommand(commandA);
    commandManager.executeCommand(commandB);

    commandManager.undoLastCommand();

    delete commandA;
    delete commandB;

    return 0;
}

这样,我们就实现了一个简单的命令模式的撤销功能。当然,实际应用中可能需要根据具体需求对这个实现进行扩展和优化。

0