| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- #include "CommandModel.h"
- /* 设置命令 */
- void CommandModel::RemoteControl::setCommand(int slot, AbstractCommand* command)
- {
- m_commands[slot].push_back(command);
- m_undoCommands[slot] = nullptr;
- }
- /* 执行命令 */
- void CommandModel::RemoteControl::pressButton(int dev)
- {
- if(m_commands[dev].empty())
- {
- SPDLOG_WARN("设备:{} 没有任何命令设置", dev);
- return;
- }
- if (m_commands.find(dev) != m_commands.end())
- {
- AbstractCommand* command = m_commands[dev].front();
- command->execute();
- m_undoCommands[dev] = command;
- m_commands[dev].pop_front();
- } else {
- SPDLOG_WARN("设备 {} 没有命令设置", dev);
- }
- }
- /* 撤销命令 */
- void CommandModel::RemoteControl::pressUndo(int dev, int count)
- {
- if(m_undoCommands[dev] == nullptr)
- {
- SPDLOG_WARN("设备 {} 没有可撤销的命令", dev);
- return;
- }
- if (m_undoCommands.find(dev) != m_undoCommands.end())
- {
- m_undoCommands[dev]->undo();
- m_undoCommands[dev] = nullptr;
- } else {
- SPDLOG_WARN("设备 {} 没有可撤销的命令", dev);
- }
- }
- /* 使用遥控器 */
- void CommandModel::useRemoteControl()
- {
- /* 创建设备 */
- Light* light = new Light();
- TV* tv = new TV();
- /* 创建命令 */
- AbstractCommand* lightOnCommand = new LightOnCommand(light);
- AbstractCommand* lightOffCommand = new LightOffCommand(light);
- AbstractCommand* tvOnCommand = new TVOnCommand(tv);
- AbstractCommand* tvOffCommand = new TVOffCommand(tv);
- /* 创建遥控器 */
- RemoteControl remote;
- SPDLOG_INFO("按下按钮,打开灯光...");
- remote.setCommand(1, lightOnCommand);
- remote.pressButton(1);
- SPDLOG_INFO("按下按钮,关闭灯光...");
- remote.setCommand(1, lightOffCommand);
- remote.pressButton(1);
- SPDLOG_INFO("撤销上一个操作...");
- remote.pressUndo(1);
- SPDLOG_INFO("按下按钮,打开电视...");
- remote.setCommand(2, tvOnCommand);
- remote.pressButton(2);
- SPDLOG_INFO("按下按钮,关闭电视...");
- remote.setCommand(2, tvOffCommand);
- remote.pressButton(2);
- SPDLOG_INFO("撤销上一个操作...");
- remote.pressUndo(2);
- }
|