命令模式实现撤销和重做机制
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 | #include <vector> #include <iostream> //定义命令接口 class Command { public : virtual void execute() = 0; virtual void undo() = 0; }; //实现“增加”命令类 class IncreaseCommand : public Command { private : int * _value; int _amount; public : IncreaseCommand( int * value, int amount) : _value(value), _amount(amount) { } void execute() override { *_value += _amount; } void undo() override { *_value -= _amount; } }; //实现“减少”命令类 class DecreaseCommand : public Command { private : int * _value; int _amount; public : DecreaseCommand( int * value, int amount) : _value(value), _amount(amount) { } void execute() override { *_value -= _amount; } void undo() override { *_value += _amount; } }; //实现命令管理器 class CommandManager { private : std::vector<Command*> _executedCommands; std::vector<Command*> _undoneCommands; public : CommandManager() {} ~CommandManager() { for ( auto & cmd : _executedCommands) { delete cmd; } for ( auto & cmd : _undoneCommands) { delete cmd; } } void execute(Command* command) { command->execute(); _executedCommands.push_back(command); _undoneCommands.clear(); // 清除重做命令列表 } void undo() { if (!_executedCommands.empty()) { Command* lastCommand = _executedCommands.back(); lastCommand->undo(); _undoneCommands.push_back(lastCommand); _executedCommands.pop_back(); } } void redo() { if (!_undoneCommands.empty()) { Command* lastCommand = _undoneCommands.back(); lastCommand->execute(); _executedCommands.push_back(lastCommand); _undoneCommands.pop_back(); } } }; int main() { int value = 10; CommandManager manager; // 增加 5 manager.execute( new IncreaseCommand(&value, 5)); std::cout << "Value: " << value << std::endl; // 输出: 15 // 减少 3 manager.execute( new DecreaseCommand(&value, 3)); std::cout << "Value: " << value << std::endl; // 输出: 12 // 撤销 manager.undo(); std::cout << "Value: " << value << std::endl; // 输出: 15 // 重做 manager.redo(); std::cout << "Value: " << value << std::endl; // 输出: 12 return 0; } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律