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