设计模式之单件模式

单件模式

定义

确保一个类只有一个实例,并提供一个全局访问点。

类图

CahCGR.jpg

代码示例

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
class Singleton {
public:
static Singleton* getInstance() {
if (instance == nullptr) {
instance = new Singleton();
}
return instance;
}

void hello() {
cout << "singleton:hello" << endl;
}

private:
Singleton() {};

static Singleton* instance;
};

//线程安全
class Singleton {
public:
static Singleton* getInstance() {
if (instance == nullptr) {
lock.lock();
instance = new Singleton();
lock.unlock();
}
return instance;
}

void hello() {
cout << "singleton:hello" << endl;
}

private:
Singleton() {};

static Singleton* instance;
static MutexLock lock;
};

理解

相当于全局变量,只有一个实例,全局共享,只能通过函数来取得实例,将构造函数声明为私有,有必要的话,将拷贝构造和赋值也声明为私有。

分享到