Bridge++  Version 1.4.4
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
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  exit(EXIT_FAILURE);
62 
63  return 0;
64  }
65  }
66 
67  bool append(const IdentifierType& subtype, ProductCreator creator)
68  {
69  if ((m_map.find(subtype) == m_map.end()) &&
70  m_map.insert(typename Map::value_type(subtype, creator)).second) {
71  return true;
72  } else {
73  fprintf(stderr, "Factory::append: duplicate key \"%s\"\n", subtype.c_str());
74  return false;
75  }
76  }
77 
79  {
80  if (!s_instance) {
81  // lock
82  if (!s_instance) {
84  }
85  // unlock
86  }
87  return *s_instance;
88  }
89 
90  private:
92 
93  // singleton
97 
98  virtual ~FactoryTemplate() {}
99 
100  static inline void create_instance()
101  {
102  static FactoryTemplate instance;
103 
104  s_instance = &instance;
105  }
106 
108 };
109 
110 template<class AbstractProduct, typename ProductCreator>
112 #endif
static FactoryTemplate & Instance()
Definition: factory.h:78
static bool Register(const IdentifierType &subtype, ProductCreator creator)
Definition: factory.h:48
static void create_instance()
Definition: factory.h:100
static ProductCreator Find(const IdentifierType &subtype)
Definition: factory.h:43
static FactoryTemplate * s_instance
Definition: factory.h:107
bool append(const IdentifierType &subtype, ProductCreator creator)
Definition: factory.h:67
virtual ~FactoryTemplate()
Definition: factory.h:98
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:95
std::string IdentifierType
Factory template class.
Definition: factory.h:33