CommandModel.cpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #include "CommandModel.h"
  2. /* 设置命令 */
  3. void CommandModel::RemoteControl::setCommand(int slot, AbstractCommand* command)
  4. {
  5. m_commands[slot].push_back(command);
  6. m_undoCommands[slot] = nullptr;
  7. }
  8. /* 执行命令 */
  9. void CommandModel::RemoteControl::pressButton(int dev)
  10. {
  11. if(m_commands[dev].empty())
  12. {
  13. SPDLOG_WARN("设备:{} 没有任何命令设置", dev);
  14. return;
  15. }
  16. if (m_commands.find(dev) != m_commands.end())
  17. {
  18. AbstractCommand* command = m_commands[dev].front();
  19. command->execute();
  20. m_undoCommands[dev] = command;
  21. m_commands[dev].pop_front();
  22. } else {
  23. SPDLOG_WARN("设备 {} 没有命令设置", dev);
  24. }
  25. }
  26. /* 撤销命令 */
  27. void CommandModel::RemoteControl::pressUndo(int dev, int count)
  28. {
  29. if(m_undoCommands[dev] == nullptr)
  30. {
  31. SPDLOG_WARN("设备 {} 没有可撤销的命令", dev);
  32. return;
  33. }
  34. if (m_undoCommands.find(dev) != m_undoCommands.end())
  35. {
  36. m_undoCommands[dev]->undo();
  37. m_undoCommands[dev] = nullptr;
  38. } else {
  39. SPDLOG_WARN("设备 {} 没有可撤销的命令", dev);
  40. }
  41. }
  42. /* 使用遥控器 */
  43. void CommandModel::useRemoteControl()
  44. {
  45. /* 创建设备 */
  46. Light* light = new Light();
  47. TV* tv = new TV();
  48. /* 创建命令 */
  49. AbstractCommand* lightOnCommand = new LightOnCommand(light);
  50. AbstractCommand* lightOffCommand = new LightOffCommand(light);
  51. AbstractCommand* tvOnCommand = new TVOnCommand(tv);
  52. AbstractCommand* tvOffCommand = new TVOffCommand(tv);
  53. /* 创建遥控器 */
  54. RemoteControl remote;
  55. SPDLOG_INFO("按下按钮,打开灯光...");
  56. remote.setCommand(1, lightOnCommand);
  57. remote.pressButton(1);
  58. SPDLOG_INFO("按下按钮,关闭灯光...");
  59. remote.setCommand(1, lightOffCommand);
  60. remote.pressButton(1);
  61. SPDLOG_INFO("撤销上一个操作...");
  62. remote.pressUndo(1);
  63. SPDLOG_INFO("按下按钮,打开电视...");
  64. remote.setCommand(2, tvOnCommand);
  65. remote.pressButton(2);
  66. SPDLOG_INFO("按下按钮,关闭电视...");
  67. remote.setCommand(2, tvOffCommand);
  68. remote.pressButton(2);
  69. SPDLOG_INFO("撤销上一个操作...");
  70. remote.pressUndo(2);
  71. }