SimpleAI
 All Classes Namespaces Files Functions Variables Typedefs Macros Groups Pages
IFactoryRegistry.h
Go to the documentation of this file.
1 
4 #pragma once
5 
6 #include "common/Types.h"
7 #include "common/NonCopyable.h"
8 #include <memory>
9 #include <map>
10 
11 namespace ai {
12 
13 template<class TYPE, class CTX>
14 class IFactory {
15 public:
16  virtual ~IFactory() {}
17  virtual std::shared_ptr<TYPE> create (const CTX* ctx) const = 0;
18 };
19 
20 template<class KEY, class TYPE, class CTX>
22 protected:
23  typedef std::map<const KEY, const IFactory<TYPE, CTX>*> FactoryMap;
24  typedef typename FactoryMap::const_iterator FactoryMapConstIter;
25  typedef typename FactoryMap::iterator FactoryMapIter;
26  FactoryMap _factories;
27 public:
28  bool registerFactory (const KEY& type, const IFactory<TYPE, CTX>& factory)
29  {
30  FactoryMapConstIter i = _factories.find(type);
31  if (i != _factories.end()) {
32  return false;
33  }
34 
35  _factories[type] = &factory;
36  return true;
37  }
38 
39  bool unregisterFactory (const KEY& type)
40  {
41  FactoryMapIter i = _factories.find(type);
42  if (i == _factories.end()) {
43  return false;
44  }
45 
46  _factories.erase(i);
47  return true;
48  }
49 
50  std::shared_ptr<TYPE> create (const KEY& type, const CTX* ctx = nullptr) const
51  {
52  FactoryMapConstIter i = _factories.find(type);
53  if (i == _factories.end()) {
54  return std::shared_ptr<TYPE>();
55  }
56 
57  const IFactory<TYPE, CTX>* factory = i->second;
58 
59 #if AI_EXCEPTIONS
60  try {
61 #endif
62  return factory->create(ctx);
63 #if AI_EXCEPTIONS
64  } catch (...) {
65  ai_log_error("Exception while trying to create a factory");
66  }
67  return std::shared_ptr<TYPE>();
68 #endif
69  }
70 };
71 
72 }
#define ai_log_error(...)
Logging macro to provide your own loggers.
Definition: Types.h:23
Definition: IFactoryRegistry.h:14
Definition: NonCopyable.h:8
Definition: IFactoryRegistry.h:21