Skip to content

Commit 330e2ae

Browse files
committed
Create factory.h
1 parent 4b1ccf8 commit 330e2ae

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

factory.h

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
#ifndef __FACTORY_H__
2+
#define __FACTORY_H__
3+
4+
#include <string>
5+
#include <map>
6+
#include <cassert>
7+
8+
template<typename TBase, typename TKey = std::string>
9+
class Factory
10+
{
11+
public:
12+
static Factory* instance() {
13+
static Factory singleton;
14+
return &singleton;
15+
}
16+
17+
struct BuilderBase
18+
{
19+
virtual TBase* create() = 0;
20+
};
21+
22+
template<typename TDerived>
23+
struct Builder : public BuilderBase
24+
{
25+
Builder(const TKey& id) {
26+
Factory<TBase, TKey>::instance()->register_builder(id, this);
27+
}
28+
TBase* create() { return new TDerived; }
29+
};
30+
31+
TBase* create(const TKey& id) const {
32+
std::map<TKey, BuilderBase*>::const_iterator it = m_builders.find(id);
33+
return (it == m_builders.end()) ? NULL : it->second->create();
34+
}
35+
36+
void register_builder(const TKey& id, BuilderBase* bb) {
37+
std::pair<std::map<TKey, BuilderBase*>::iterator, bool> p =
38+
m_builders.insert(std::make_pair(id, bb));
39+
assert(p.second); // builder 'id' already registered
40+
}
41+
42+
private:
43+
Factory() {}
44+
~Factory() {}
45+
Factory(const Factory&);
46+
Factory& operator=(const Factory&);
47+
48+
std::map<TKey, BuilderBase*> m_builders;
49+
};
50+
51+
#endif

0 commit comments

Comments
 (0)