Bridge++  Ver. 1.3.x
factory.h
Go to the documentation of this file.
1 
14 #ifndef FACTORY_INCLUDED
15 #define FACTORY_INCLUDED
16 
18 
30 #include <string>
31 #include <map>
32 
33 typedef std::string IdentifierType;
34 
35 template<class AbstractProduct, typename ProductCreator>
37 {
38  private:
39  typedef std::map<IdentifierType, ProductCreator> Map;
40 
41 
42  public:
43  static ProductCreator Find(const IdentifierType& subtype)
44  {
45  return Instance().find(subtype);
46  }
47 
48  static bool Register(const IdentifierType& subtype, ProductCreator creator)
49  {
50  return Instance().append(subtype, creator);
51  }
52 
53  ProductCreator find(const IdentifierType& subtype)
54  {
55  typename Map::const_iterator i = m_map.find(subtype);
56  if (i != m_map.end()) {
57  return i->second;
58  } else {
59  fprintf(stderr, "Factory::find: unknown type \"%s\"\n", subtype.c_str());
60 
61 #ifdef DEBUG
62  exit(EXIT_FAILURE);
63 #endif
64 
65  return 0;
66  }
67  }
68 
69  bool append(const IdentifierType& subtype, ProductCreator creator)
70  {
71  if ((m_map.find(subtype) == m_map.end()) &&
72  m_map.insert(typename Map::value_type(subtype, creator)).second) {
73  return true;
74  } else {
75  fprintf(stderr, "Factory::append: duplicate key \"%s\"\n", subtype.c_str());
76  return false;
77  }
78  }
79 
81  {
82  if (!s_instance) {
83  // lock
84  if (!s_instance) {
86  }
87  // unlock
88  }
89  return *s_instance;
90  }
91 
92  private:
93  Map m_map;
94 
95  // singleton
99 
100  virtual ~FactoryTemplate() {}
101 
102  static inline void create_instance()
103  {
104  static FactoryTemplate instance;
105 
106  s_instance = &instance;
107  }
108 
110 };
111 
112 template<class AbstractProduct, typename ProductCreator>
114 #endif
static FactoryTemplate & Instance()
Definition: factory.h:80
static bool Register(const IdentifierType &subtype, ProductCreator creator)
Definition: factory.h:48
static void create_instance()
Definition: factory.h:102
static ProductCreator Find(const IdentifierType &subtype)
Definition: factory.h:43
static FactoryTemplate * s_instance
Definition: factory.h:109
bool append(const IdentifierType &subtype, ProductCreator creator)
Definition: factory.h:69
virtual ~FactoryTemplate()
Definition: factory.h:100
std::map< IdentifierType, ProductCreator > Map
Definition: factory.h:39
ProductCreator find(const IdentifierType &subtype)
Definition: factory.h:53
FactoryTemplate & operator=(const FactoryTemplate &)
FactoryTemplate(const FactoryTemplate &)
Definition: factory.h:97
std::string IdentifierType
Factory template class.
Definition: factory.h:33