-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMultiton.h
78 lines (58 loc) · 1.7 KB
/
Multiton.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#ifndef BaseLib_Multiton_h_IsIncluded
#define BaseLib_Multiton_h_IsIncluded
#include <map>
namespace BaseLib
{
/**
@description Implementation of Multiton software pattern.
class Foo : public Multiton<std::string, Foo> {};
Foo& foo1 = Foo::getRef("foobar");
Foo* foo2 = Foo::getPtr("foobar");
Foo::destroy();
class Foo : public Multiton<Foo> {};
class Bar : public Multiton<Bar,int> {};
@url http://stackoverflow.com/questions/2346091/c-templated-class-implementation-of-the-multiton-pattern
*/
template <typename Key, typename T>
class Multiton
{
public:
static void Destroy()
{
for (typename std::map<Key, T*>::iterator it = instances.begin(); it != instances.end(); ++it) {
delete (*it).second;
}
}
static T& GetRef(const Key& key)
{
typename std::map<Key, T*>::iterator it = instances.find(key);
if(it != instances.end())
{
return *(T*)(it->second);
}
T* instance = new T;
instances[key] = instance;
return *instance;
}
static T* GetPtr(const Key& key)
{
typename std::map<Key, T*>::iterator it = instances.find(key);
if(it != instances.end())
{
return (T*)(it->second);
}
T* instance = new T;
instances[key] = instance;
return instance;
}
protected:
Multiton() {}
virtual ~Multiton() {}
private:
Multiton(const Multiton&) {}
Multiton& operator = (const Multiton&) { return *this; }
static std::map<Key, T*> instances;
};
template <typename Key, typename T> std::map<Key, T*> Multiton<Key, T>::instances;
} // namespace BaseLib
#endif // BaseLib_Multiton_h_IsIncluded