[ 设计模式 ] | 单例模式

单例模式是什么?哪两种模式?

单例模式就是一个类型的对象,只有一个,比如说搜索引擎中的索引部分,360安全卫士的桌面悬浮球。

饿汉模式和懒汉模式:饿汉模式是线程安全的,懒汉模式不是线程安全的,但是我们可以为其加锁,实现成线程安全的。

饿汉单例模式的代码实现

单例模式的实现主要在于将构造函数私有化,并且将拷贝构造和赋值拷贝禁用。

饿汉,这个对象在main函数执行之前就创建对象。

cpp 复制代码
class Single
{
public:
	static Single* getInstance()
	{
		return &instance;
	}
private:
	static Single instance;
	Single()
	{
	}
	Single(const Single&) = delete;
	Single &operator=(const Single&) = delete;
};
Single Single::instance;

饿汉单例模式的问题

如果系统中有多个饿汉的对象,可能会造成系统启动过慢的问题。

懒汉单例模式的代码实现

懒汉,就是在使用这个对象的时候再去创建这个对象。

1.

基本实现,不是线程安全的。

cpp 复制代码
class Single
{
public:
	static Single* getInstance()
	{
		if (instance == nullptr)
		{
			lock_guard<std::mutex> guard(mtx);
			if (instance == nullptr)
				instance = new Single();
		}
		return instance;
	}
private:
	static Single * volatile instance;
	Single()
	{
	}
	Single(const Single&) = delete;
	Single& operator=(const Single&) = delete;
};
Single * volatile Single::instance = nullptr;

2.

为其加锁,线程安全的。

两层判断,避免锁的粒度太大,单线程环境下也会加锁。

cpp 复制代码
std::mutex mtx;

class Single
{
public:
	Single* getInstance()
	{
		if (instance == nullptr)
		{
			lock_guard<std::mutex> guard(mtx);
			if (instance == nullptr)
				instance = new Single();
		}
		return instance;
	}
private:
	static Single * volatile instance;
	Single()
	{
	}
	Single(const Single&) = delete;
	Single& operator=(const Single&) = delete;
};
Single * volatile Single::instance = nullptr;

3.

cpp 复制代码
class Single
{
public:
	static Single* getInstance()
	{
		static Single instance;
		return &instance;
	}
private:
	Single()
	{
	}
	Single(const Single&) = delete;
	Single& operator=(const Single&) = delete;
};

这种实现方法,我们主要探讨是不是线程安全的?我们将这段代码反汇编之后,可以发现,操作系统会在创建的时候为其加锁的,证明他是线程安全的~~

相关推荐
我叫黑大帅22 分钟前
什么是 mmap?
linux·c++·操作系统
玖笙&31 分钟前
✨WPF编程基础【1.2】:XAML中的属性
c++·wpf·visual studio
举焰1 小时前
VSCode+MSVC+Qmake环境搭建笔记
c++·ide·笔记·vscode·msvc·qt5·qmake
耿直小伙2 小时前
UI界面点击按钮一直转圈假死
c++·ui
我是华为OD~HR~栗栗呀2 小时前
测试转C++开发面经(华为OD)
java·c++·后端·python·华为od·华为·面试
qiu_zhongya2 小时前
iree 用C++来运行Qwen 2.5 0.5b
开发语言·c++·人工智能
汪宁宇2 小时前
giflib5.2.2 在Qt与VS C++中实现Gif缩放示例
开发语言·c++·qt
啊?啊?2 小时前
C/C++练手小项目之倒计时与下载进度条模拟
c语言·开发语言·c++
西阳未落2 小时前
C++基础(22)——模板的进阶
开发语言·c++
waves浪游3 小时前
C++模板进阶
开发语言·c++