-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSingleton.hpp
75 lines (71 loc) · 1.96 KB
/
Singleton.hpp
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
#ifndef __SINGLETON_HPP__
#define __SINGLETON_HPP__
#include <cstdlib>
#include <iostream>
#include <memory>
#include <string>
#include <unordered_map>
namespace peking {
class Singleton {
public:
using Ptr = std::shared_ptr<Singleton>;
using Registry = std::unordered_map<std::string, Ptr>;
static void Register(const std::string &name, const Ptr ptr) {
auto iter = registry_.find(name);
if (iter != registry_.end()) {
std::cout << "Already registered: " << name << std::endl;
return;
} else {
// magic &
registry_.insert(std::make_pair<const std::string &, const Ptr &>(name, ptr));
// registry_.insert({name, ptr});
}
}
protected:
Singleton() {
std::cout << "Base Singleton" << std::endl;
}
static Ptr LookUp(const std::string &name) {
auto iter = registry_.find(name);
if (iter == registry_.end()) {
std::cout << "Type " << name << " is not registerd." << std::endl;
return ptr_;
} else {
return iter->second;
}
}
private:
static Ptr ptr_;
// for looking up, hash is considered first.
static Registry registry_;
public:
// lazy or hungry
// volatile
static Ptr Instance() {
if (ptr_.get() == nullptr) {
auto c_name = getenv("HOME");
const std::string name(c_name);
std::cout << name << std::endl;
ptr_ = LookUp(name);
if (ptr_.get() == nullptr) {
ptr_ = Ptr(new Singleton());
}
std::cout << "Created ";
}
std::cout << ptr_.use_count() << std::endl;
return ptr_;
}
};
Singleton::Ptr Singleton::ptr_ = nullptr;
Singleton::Registry Singleton::registry_ = Registry();
// Intention: make some special son-class representing different config,
// Let the code dynamically produce config corresponding to the `getenv()`
class MySingleton : public Singleton {
public:
MySingleton() : Singleton() {
std::cout << "My dream" << std::endl;
Register("Safer Car", Singleton::Ptr(this));
}
};
} // namespace peking
#endif