-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsingleton.h
68 lines (57 loc) · 1014 Bytes
/
singleton.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
#include <iostream>
//单线程
template <typename T>
class Singleton
{
private:
static T* _value;
public:
static T& getInstance(){
if(_value==NULL)
_value=new T();
return _value;
}
private:
Singleton();
~Singleton();
};
template<typename T>
T* Singleton<T>::_value=NULL;
//<effective C++>中的写法
template<typename T>
class Singleton
{
public:
static T& getInstance(){
staic T value;
return value;
}
private:
Singleton();
~Singleton();
};
//多线程
template<typename T>
class Singleton
{
private:
static pthread_once_t _once_control;
static T* _value;
public:
static T& getInstance()
{
pthread_once(&_once_control, init);
return *_value;
}
private:
static void init()
{
_value=new T();
}
Singleton();
~Singleton();
};
template<typename T>
pthread_once_t Singleton<T>::_once_control=PTHREAD_ONCE_INIT;
template<typename T>
T *Singleton<T>::_value=NULL;