设计场景:
在整个系统周期内,保证一个类只有唯一的一个实例被创建;
问题描述:
(1)单例模式:保证一个类仅有一个实例,并提供一个访问它的全局访问点;
(2)通常我们可以让一个全局变量使得一个对象被访问,但是它不能防止你实例化多个对象,一个最好的方法就是,让类自身负责保存它的唯一实例,这个类可以保证没有其他实例可以被创建,并且它提供一个访问该实例的方法;
(3)单例模式分为懒汉式和饿汉式,区别在于创建实例的时间不同,同时还要考虑其线程安全性;
(4)懒汉式:程序运行中,实例并不存在,只有当需要该实例时,才会创建并使用实例,即当调用getInstance()函数时才会创建实例,需要考虑线程安全;
(5)饿汉式:程序一运行,就初始化创建实例,当需要时,直接调用即可,本身就线程安全,不存在多线程的问题;
(6)懒汉式是以时间换空间,适应于访问量较小时;推荐使用内部静态变量的懒汉单例,代码量少
(7)饿汉式是以空间换时间,适应于访问量较大时,或者线程比较多的的情况
代码实现:
主函数(不考虑多线程):
#include"Singleton.h"
#include<iostream>
using namespace std;
int main()
{
Singleton* s1 = Singleton::getInstance();
Singleton* s2 = Singleton::getInstance();
if (s1 == s2)
{
cout << "两个对象是相同的实例" << endl;
}
system("pause");
return 0;
}
一、懒汉式单例模式(不考虑多线程):
#pragma once
#include <cstddef>
class Singleton
{
public:
// 获取单实例
static Singleton* getInstance()
{
if (m_instance == nullptr)
{
m_instance = new Singleton();
}
return m_instance;
}
// 释放单实例,进程退出时调用
static void delInstance()
{
if (m_instance != nullptr)
{
delete m_instance;
m_instance = nullptr;
}
}
private:
// 将构造、析构私有化,禁止外部构造和析构
Singleton(){}
~Singleton(){}
// 声明唯一对象指针
static Singleton* m_instance;
};
// 懒汉式
// 程序一运行不创建实例,等使用时才通过new创建实例,存在多线程安全
Singleton* Singleton::m_instance = nullptr;
二、懒汉式单例模式(考虑多线程):
#pragma once
#include <mutex>
using namespace std;
class Singleton
{
public:
// 获取单实例
static Singleton* getInstance()
{
// 双检锁,只有判断指针为空的时候才加锁,避免每次调用 getInstance()都加锁,锁的开销毕竟还是有点大的
if (m_instance == nullptr)
{
// 加锁
unique_lock<mutex> lock(m_Mutex);
// 实例化
if (m_instance == nullptr)
{
m_instance = new Singleton();
}
m_instance = new Singleton();
}
// 返回实例
return m_instance;
}
// 释放单实例,进程退出时调用
static void delInstance()
{
// 加锁
unique_lock<mutex> lock(m_Mutex);
// 注销实例化
if (m_instance != nullptr)
{
delete m_instance;
m_instance = nullptr;
}
}
private:
// 将构造、析构私有化,禁止外部构造和析构
Singleton(){}
~Singleton(){}
// 声明唯一单实例对象指针
static Singleton* m_instance;
// 互斥锁
static mutex m_Mutex;
};
// 饿汉式
// 程序一运行就初始化创建实例,本身就线程安全
Singleton* Singleton::m_instance; // (默认初始化)
mutex Singleton::m_Mutex; // (默认初始化)
三、饿汉式单例模式:
#pragma once
#include <cstddef>
class Singleton
{
public:
// 获取单实例
static Singleton* getInstance()
{
if (m_instance == nullptr)
{
m_instance = new Singleton();
}
return m_instance;
}
// 释放单实例,进程退出时调用
static void delInstance()
{
if (m_instance != nullptr)
{
delete m_instance;
m_instance = nullptr;
}
}
private:
// 将构造、析构私有化,禁止外部构造和析构
Singleton(){}
~Singleton(){}
// 声明唯一单实例对象指针
static Singleton* m_instance;
};
// 饿汉式
// 程序一运行就初始化创建实例,本身就线程安全
Singleton* Singleton::m_instance = new Singleton();