单例模式

概述

23种设计模式中的一种,要求通过一个类只能创建一个对象

应用场景

  1. 单例模式可以用来替换全局变量
  2. 配置文件中的信息可以存储在单例对象中
  3. 网页库,倒排索引库都可以使用单例模式

步骤

  1. 在类中定义一个静态的指向本类型的指针
  2. 将构造函数私有化
  3. 在public中定义一个静态成员函数

代码实现

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
#include <iostream>
using namespace std;

class PInstance{
public:
//通过getinstance来获得一个单例类,设置为静态的就没有this指针了
//可以在类外直接调用
static PInstance* getInstance(){
if(_instance == nullptr){
_instance = new PInstance();
return _instance;
}
}
static void deleteInstance(){
if(_instance){
delete _instance;
}
}
//构造函数私有化,因为单例模式就是一个类只能创建一个对象
//构造函数私有化后就无法构造多个对象了
private:
PInstance(){
}
//为了使构造单例对象和删除单例对象的格式统一,把析构函数的
//访问权限也设置为私有
~PInstance(){}
private:
//数据成员
static PInstance *_instance;
};
//静态数据成员变量初始化
PInstance *PInstance::_instance = nullptr;

void test(){
PInstance *p1 = PInstance::getInstance();
PInstance *p2 = PInstance::getInstance();

cout<<p1<<endl;
cout<<p2<<endl;

PInstance::deleteInstance();


}


int main()
{
test();
std::cout << "Hello world" << std::endl;
return 0;
}

效果

单例模式效果

发现生成的两个对象地址是一样的,说明这是一个对象,实现了单例模式的要求

没有出现内存泄漏

删除指针后也没有出现内存泄漏