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