-
Notifications
You must be signed in to change notification settings - Fork 1
/
multiton.cpp
62 lines (54 loc) · 1.18 KB
/
multiton.cpp
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
#include <map>
#include <memory>
#include <iostream>
using namespace std;
enum class Importance
{
primary,
secondary,
tertiary
};
template <typename T, typename Key = std::string>
class Multiton
{
public:
static shared_ptr<T> get(const Key& key)
{
if (const auto it = instances.find(key);
it != instances.end())
{
return it->second;
}
auto instance = make_shared<T>();
instances[key] = instance;
return instance;
}
protected:
Multiton() = default;
virtual ~Multiton() = default;
private:
static map<Key, shared_ptr<T>> instances;
};
template <typename T, typename Key>
map<Key, shared_ptr<T>> Multiton<T, Key>::instances;
class Printer
{
public:
Printer()
{
++Printer::totalInstanceCount;
cout << "A total of " <<
Printer::totalInstanceCount <<
" instances created so far\n";
}
private:
static int totalInstanceCount;
};
int Printer::totalInstanceCount = 0;
int main()
{
typedef Multiton<Printer, Importance> mt;
auto main = mt::get(Importance::primary);
auto aux = mt::get(Importance::secondary);
auto aux2 = mt::get(Importance::secondary);
}