0%

单例模式

2020年5月23日 下午12:09

单例模式的思路:

  1. 从需求的角度:
    1. 我们需要一个单独的方法来判断当前Singleton类是否有已有对象存在,如果存在就直接返回对象
      1. 注意:这里返回的必须是指向对象的指针,不能生成临时对象
      2. Singleton* getInstance()
    2. 这个好像很容易实现,但是如果我们为了安全要求用户不能使用构造函数
      1. private:Singleton(){};
    3. 在1,2这两个需求下,我们只能使用静态static成员方法和变量,才可能同时做到1,2,并且静态成员方法只能操作静态变量,所以我们要
      1. static Singleton* This;
      2. static const Singleton* getInstance()
  2. 两种模式的区别:
    1. C++ 线程安全的单例模式总结 - 掘金
    2. 单例模式可以分为懒汉式饿汉式,两者之间的区别在于创建实例的时间不同
      1. 懒汉式:指系统运行中,实例并不存在,只有当需要使用该实例时,才会去创建并使用实例。(这种方式要考虑线程安全)
      2. 饿汉式:指系统一运行,就初始化创建实例,当需要时,直接调用即可。(本身就线程安全,没有多线程的问题)
        1. Singleton* Singleton::This = new Singleton;

附录代码:懒汉模式,非线程安全

1
2
3
4
5
6
7
8
int main()
{
Singleton::getInstance()->DoSomething();

Singleton::getInstance()->DoSomething();

return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#pragma once

#include <iostream>
using namespace std;
class Singleton
{
public:
static const Singleton* getInstance();
static void DoSomething()
{
cout << "Do Something" << endl;
}
// 将构造和析构函数私有化,防止外部访问
private:
Singleton(){};
~Singleton(){};

static Singleton* This; // 使用静态变量帮助解决资源的分配和释放
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include "stdafx.h"
#include "Singleton.h"

Singleton* Singleton::This = nullptr;
const Singleton* Singleton::getInstance()
{
if (!This)
{
This = new Singleton();
}
return This;
}
//
//Singleton::Singleton()
//{
//}
//
//Singleton::~Singleton()
//{
//}