#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;
}