BeeeOn Gateway  v2020.3.1-2-g6f737dc
Platform to interconnect the IoT world
DIFactory.h
1 #pragma once
2 
3 #include <string>
4 #include <typeinfo>
5 
6 #include <Poco/SharedPtr.h>
7 
8 namespace BeeeOn {
9 
10 class DIWrapper;
11 class DIWCast;
12 
18 class DIFactory {
19 public:
20  typedef Poco::SharedPtr<DIFactory> Ptr;
21 
22  virtual ~DIFactory();
23 
31  const std::string &name,
32  bool detach = false)
33  {
34  return createImpl(name, detach);
35  }
36 
42  template <typename T>
43  Poco::SharedPtr<T> create(
44  const std::string &name,
45  bool detach = false)
46  {
47  auto wrapper = create(name, detach);
48  if (wrapper == nullptr)
49  return {};
50 
51  return cast<T>(*wrapper);
52  }
53 
58  DIWrapper *find(const std::string &name)
59  {
60  return findImpl(name);
61  }
62 
68  template <typename T>
69  Poco::SharedPtr<T> find(const std::string &name)
70  {
71  auto wrapper = findImpl(name);
72  if (wrapper == nullptr)
73  return {};
74 
75  return cast<T>(*wrapper);
76  }
77 
78 protected:
83  template <typename T>
84  Poco::SharedPtr<T> cast(DIWrapper &wrapper)
85  {
86  Poco::SharedPtr<T> instance;
87  castImpl(typeid(T), wrapper, reinterpret_cast<void *>(&instance));
88 
89  return instance;
90  }
91 
96  virtual DIWrapper *findImpl(const std::string &name) = 0;
97 
103  virtual DIWrapper *createImpl(
104  const std::string &name,
105  bool detach) = 0;
106 
112  virtual void castImpl(
113  const std::type_info &type,
114  const DIWrapper &wrapper,
115  void *target) = 0;
116 
117 };
118 
119 }
virtual DIWrapper * createImpl(const std::string &name, bool detach)=0
Poco::SharedPtr< T > create(const std::string &name, bool detach=false)
Create a new instance by name and perform runtime cast to the target type if possible.
Definition: DIFactory.h:43
DIWrapper * find(const std::string &name)
Find an existing instance and return it.
Definition: DIFactory.h:58
Poco::SharedPtr< T > find(const std::string &name)
Find an existing instance and cast it to the target type if possible.
Definition: DIFactory.h:69
Definition: DIWrapper.h:386
Implementation of DIFactory can manage and create instances by name and automatically (usually based ...
Definition: DIFactory.h:18
DIWrapper * create(const std::string &name, bool detach=false)
Create a new instance by name. If detached is true, the memory of the returned DIWrapper pointer MUST...
Definition: DIFactory.h:30
Poco::SharedPtr< T > cast(DIWrapper &wrapper)
Cast the wrapped instance to the target type. If the cast is not possible, throw an exception...
Definition: DIFactory.h:84
virtual void castImpl(const std::type_info &type, const DIWrapper &wrapper, void *target)=0
Perform cast of the given wrapper to the target of the given type. The target points to the Poco::Sha...
virtual DIWrapper * findImpl(const std::string &name)=0