单例模式
爱吃鱼的猫 Lv2

饿汉模式

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
#include <iostream>

using namespace std;

class HungrySingleton{
private:
int count = 0;
static HungrySingleton* instance;
HungrySingleton() = default;
public:
~HungrySingleton() = default;
static HungrySingleton* getInstance(){
return instance;
}
void showMessage(){
cout<<count<<endl;
}
};

/* 初始化类静态变量 */
HungrySingleton* HungrySingleton::instance = new HungrySingleton();

int main(){
HungrySingleton* object = HungrySingleton::getInstance();
object->showMessage();
return 0;
}

懒汉模式

线程安全(双重校验锁)

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
#include <iostream>
#include <mutex>

using namespace std;

class LazySingleton{
private:
static LazySingleton* instance;
static mutex _lock;
int count = 1;
LazySingleton() = default;
public:
~LazySingleton() = default;
static LazySingleton* getInstance(){
/* 缩小锁粒度,提高效率 */
if(instance==nullptr){
lock_guard<mutex> locker(_lock);
if(instance== nullptr){
instance = new LazySingleton;
}
}
return instance;
}
void showMessage(){
cout<<count;
}
};

/* 初始化类静态变量 */
mutex LazySingleton::_lock;
LazySingleton* LazySingleton::instance = nullptr;

int main() {
LazySingleton* object = LazySingleton::getInstance();
object->showMessage();
return 0;
}

线程安全(局部静态变量)

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
#include <iostream>

class LazySingleton{
private:
int count = 1;
LazySingleton() = default;
public:
~LazySingleton() = default;
static LazySingleton* getInstance(){
/* 局部静态变量只会在第一次声明的时候初始化,在c++11以及之后的版本可以做到线程安全
1.变量在代码第一次执行到变量声明的地方时初始化。
2.初始化过程中发生异常的话视为未完成初始化,未完成初始化的话,需要下次有代码执行到相同位置时再次初始化。
3.在当前线程执行到需要初始化变量的地方时,如果有其他线程正在初始化该变量,则阻塞当前线程,直到初始化完成为止。
4.如果初始化过程中发生了对初始化的递归调用,则视为未定义行为
*/
static LazySingleton instance;
return &instance;
}
void showMessage(){
cout<<count;
}
};

int main() {
LazySingleton* object = LazySingleton::getInstance();
object->showMessage();
return 0;
}
  • Post title:单例模式
  • Post author:爱吃鱼的猫
  • Create time:2022-04-26 21:17:23
  • Post link:https://djtang.github.io/2022/04/26/单例模式/
  • Copyright Notice:All articles in this blog are licensed under BY-NC-SA unless stating additionally.
 Comments