在C++中,实现命令模式的撤销功能需要遵循以下步骤:
class Command {
public:
virtual ~Command() {}
virtual void execute() = 0;
virtual void undo() = 0;
};
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();
}
};
#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();
}
}
};
class Receiver {
public:
void actionA() {
// 实际执行操作A
}
void undoActionA() {
// 撤销操作A
}
void actionB() {
// 实际执行操作B
}
void undoActionB() {
// 撤销操作B
}
};
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;
}
这样,我们就实现了一个简单的命令模式的撤销功能。当然,实际应用中可能需要根据具体需求对这个实现进行扩展和优化。