executor.hpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. * @brief 该模块用于接收命令并执行命令, 然后将执行结果发送回发送着.
  3. */
  4. #pragma once
  5. #include <iostream>
  6. #include <map>
  7. #include "defines.hpp"
  8. template<typename T>
  9. class SingletonIter {
  10. public:
  11. //获取单例的指针
  12. static T *iter() {
  13. static T* instance = nullptr;
  14. if (instance == nullptr) {
  15. instance = new T();
  16. instance->init();
  17. }
  18. return instance;
  19. }
  20. virtual ~SingletonIter() = default;
  21. SingletonIter(const SingletonIter &) = delete; //关闭拷贝构造函数
  22. SingletonIter &operator=(const SingletonIter &) = delete; //关闭赋值函数
  23. protected:
  24. //构造函数需要是 protected,这样子类才能继承;
  25. SingletonIter() {
  26. }
  27. virtual Error_manager init() {
  28. return Error_code::FAILED;
  29. }
  30. };
  31. template <class T>
  32. class Executor: public SingletonIter<T> {
  33. friend class SingletonIter<T>;
  34. using listenMap = std::map<std::string, void*>;
  35. public:
  36. ~Executor() = default;
  37. Error_manager init() {
  38. return Error_code::FAILED;
  39. }
  40. virtual int addListen(const std::string &topic, void* func) {
  41. listen_map.insert(std::pair<const std::string, void*>(topic, func));
  42. return true;
  43. }
  44. virtual int addListen(listenMap &listen) {
  45. listen_map.insert(listen.begin(), listen.end());
  46. return true;
  47. }
  48. virtual int setListen() {
  49. return true;
  50. }
  51. virtual int eraseListen() {
  52. return true;
  53. }
  54. virtual int clear() {
  55. listen_map.clear();
  56. return true;
  57. }
  58. virtual size_t size() {
  59. return listen_map.size();
  60. }
  61. protected:
  62. Executor() = default;
  63. protected:
  64. listenMap listen_map;
  65. };