在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;
}
這樣,我們就實現了一個簡單的命令模式的撤銷功能。當然,實際應用中可能需要根據具體需求對這個實現進行擴展和優化。