-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathpattern.h
More file actions
95 lines (76 loc) · 2.01 KB
/
pattern.h
File metadata and controls
95 lines (76 loc) · 2.01 KB
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#ifndef _PATTERN_H_
#define _PATTERN_H_
#include "config.h"
#include <memory>
#include <mutex>
DUTIL_NAMESPACE_BEGIN
//单件模式
template<typename T>
class Singleton
{
struct T_Creator {
T_Creator() { Singleton<T>::s_instance = new T();}
~T_Creator() {
Singleton<T>::destroy();
}
};
public:
static T* instance()
{
//静态变量在多线程中,VC编译不安全(GCC安全),但c++ 11规定静态变量安全(VC 2015起支持c++11的这个特性)
static T_Creator t;
return s_instance;
}
//destroy后不能再使用instance,此函数非线程安全
static void destroy()
{
if (s_instance) {
delete s_instance;
s_instance = NULL;
}
}
protected:
Singleton() {}
~Singleton() {}
private:
Singleton(const Singleton& );
Singleton& operator =(const Singleton&);
private:
static T *s_instance;
};
template<typename T> T* Singleton<T>::s_instance = NULL;
//////////////////////////////////////////////////////////////////////////
//单件模式:: 这是线程安全的版本, 加锁
template<typename T>
class Singleton_Safe
{
public:
static T* instance()
{
if (NULL == s_instance.get()) {
std::lock_guard<std::mutex> locker(&s_mutex);
if (NULL == s_instance.get()) {
s_instance.reset(new T());
}
}
return s_instance.get();
}
static void destroy()
{
s_instance.reset(NULL);
}
protected:
Singleton_Safe() {}
~Singleton_Safe() {}
private:
Singleton_Safe(const Singleton_Safe& );
Singleton_Safe& operator =(const Singleton_Safe&);
private:
static std::unique_ptr<T> s_instance;
static std::mutex s_mutex;
};
template<typename T> std::unique_ptr<T> Singleton_Safe<T>::s_instance;
template<typename T> std::mutex Singleton_Safe<T>::s_mutex;
DUTIL_NAMESPACE_END
//////////////////////////////////////////////////////////////////////////
#endif