Cpp||懒汉模式的实现

  • 懒汉模式是单例模式中的一种,旨在实现一种全局只能使用一份资源的目的。
  • 懒汉模式:在第一次实例化对象的时候调用一次构造函数,之后实例化的对象都通过单例对象指针指向第一次申请的的内存空间,从而保证了全局只有一份资源可以使用。
#include<iostream>
#include<mutex>
#include<thread>

using namespace std;

class Singleton{
public:
	static Singleton *getSingleton(){
		if (_sin == nullptr)
		{
			//添加双锁保证效率,倘若不加这个检查的话
			//当第二次来的时候也会加锁判断之后再解锁
			m_mut.lock();
			if (_sin == nullptr){

				//该层判断的目的在于保证不会再次调用构造函数
				//来多次申请资源,继而保证了单例模式的体现
				_sin = new Singleton();
			}
			m_mut.unlock();
			
		}
		return _sin;
	}
	~Singleton(){
		cout << "~Singleton()" << endl;
	}
	
	//~singleton(){
	//	//	if(_ps){
	//	//		delete _ps;
	//	//		//delete继续调用析构函数,造成无限递归
	//	//		_ps=nullptr;
	//	//	}
	//	//}
	//不可以通过上面的方式来析构对象,但是可以
	//通过内部类的方式来对该资源进行释放
	class ClearSingleton{
	public:
		~ClearSingleton(){
			if (_sin){
				delete _sin;
				_sin = nullptr;
				cout << "~ClearSingleton()" << endl;
				//目的在于查看是否调用了析构函数
			}
		}
	};
	static  ClearSingleton clear;
	// 定义一个静态成员变量,程序结束时,系统会自动调用它的析构函数从而释放单例对象
private:
	Singleton(){};
	//防止拷贝
	Singleton(const Singleton& s)=delete;
	Singleton&operator =(Singleton const&) = delete;
	static Singleton* _sin;//单例对象指针
	static mutex m_mut;//互斥锁
};

Singleton* Singleton::_sin = nullptr;
Singleton::ClearSingleton clear;
mutex Singleton::m_mut;
//注意static变量的初始化格式

void fun(){
	for (int i = 0; i < 9; i++){
		cout << Singleton::getSingleton()<< endl;
	}
}

int main(){
	Singleton *s = Singleton::getSingleton();
	Singleton *s1 = Singleton::getSingleton();
	thread t1(fun);
	thread t2(fun);
	t1.join();
	t2.join();
	return 0;
}

程序的运行结果

在这里插入图片描述

可以看到实例化的对象s和s1与其他的调用结果一样指向同一块内存空间。(单例模式的特点),由此可以看到单例模式的实现。

【总结】
1.实现单例模式中的懒汉模式相较于饿汉模式而言要复杂,但是保证了程序运行过程中的效率。
2.实现过程中需要注意:

1.需要注意析构函数的使用
2.需要注意添加互斥锁的位置
3.需要注意将拷贝构造的途径 "堵死"

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值