C++ 单例模式 懒汉式版

所有关于设计模式的代码都是在学习传智播客的设计模式教程的时候做的笔记,方便以后遗忘时回来进行复习:

#include<iostream>
#include <mutex>        //C++11标准增加的线程
using namespace std;



class Singleton
{
public:
	//提供全局访问点,提供访问点的函数也必须是静态的,否则外界就无法调用该函数
	static Singleton* GetSingleton()
	{
		//判断类的静态指针是否为NULL,为NULL才进行动态内存分配
		if (NULL == single)
		{
			single_mutext.lock();//加锁保证线程安全
                        //著名的double checked方案
                        if(NULL == single)//避免多线程中,线程进行切换时进行重复new
			    single = new Singleton();
			single_mutext.unlock();//离开作用域释放互斥锁,
			//互斥锁在保证正常生效的前提下,作用的范围越小越好,提升并发度
		}
		return single;
		
	}
	static void DeleteSingleton()
	{
		if (NULL != single)
		{ 
			cout << "删除单例对象" << endl;
			delete single;
		}
	}
protected:
private:
	static Singleton* single ;
        //由于C++的构函数并不是线程安全的,所以单例模式的懒汉式也就不是线程安全的
        static mutex single_mutext;
	//构造函数私有化
	Singleton()
	{
		cout << "构造函数被调用" << endl;
	}
};

Singleton * Singleton::single = NULL;

int main(int argc ,char **argv)
{
	//懒汉式:只有GetSingleton()函数被调用的时候,才new对象
	//在new对象实例的时候做判断====>比较懒,
	Singleton * single_example = Singleton::GetSingleton();
	Singleton * single_example2 = Singleton::GetSingleton();
	Singleton::DeleteSingleton();
	getchar();
	return 0;

}

猜你喜欢

转载自blog.csdn.net/qq_15054345/article/details/87189843