C++单例模式

#include "stdafx.h"
#include<iostream>

using namespace std;

class singleton1 //懒汉模式
{
public:
	static singleton1 *getInstance()
	{
		if(NULL == m_instance1)
		{
			//Lock(); 可自己实现Lock类,或使用boost库中的
			if(NULL == m_instance1)
			{
				m_instance1 = new singleton1();
				cout<<"singleton1 created!"<<'\n';
			}
			//Ulock();
		}
		return m_instance1;
	}
	static void destoryInstance()
	{
		if(NULL != m_instance1)
		{
			delete m_instance1;
			m_instance1 = NULL;
			cout<<"delete singleton1"<<'\n';
		}
	}
private:
	static singleton1 * m_instance1;
	singleton1(){};
};

singleton1 * singleton1::m_instance1 = NULL; //new singleton1();//懒汉式

class singleton2 //饿汉模式
{
public:
	static singleton2 *getInstance()
	{
		//因为静态初始化在程序开始时,也就是进入主函数之前,由主线程以单线程方式完成了初始化,
		//所以静态初始化实例保证了线程安全性。
		static singleton2 instance2; //局部静态变量  
		cout<<"singleton2 created!"<<'\n';
		return &instance2;
	}
private:
	singleton2(){};
};

class singleton3  //解决懒汉式的内存泄漏问题
{
public:
	static singleton3 * getInstance()
	{
		if(NULL == m_instance3)
		{
			//Lock(); 可自己实现Lock类,或使用boost库中的
			if(NULL == m_instance3)
			{
				m_instance3 = new singleton3();
				cout<<"singleton3 created!"<<'\n';
			}
			//Ulock();
		}
		return m_instance3;
	}
private:
	singleton3(){}
	static singleton3 * m_instance3;
	class Gc
	{
	private:
		~Gc()
		{
			if(m_instance3 != NULL)
			{
				delete m_instance3;
				m_instance3 = NULL;
				cout<<"delete m_instance3";
			}
		}
	};
	static Gc Gc;//定义一个静态成员变量,程序结束时,系统会自动调用它的析构函数  
};
singleton3 * singleton3::m_instance3 = NULL;

int main()
{
	singleton1 * instance1_1 = singleton1::getInstance();
	singleton1 * instance1_2 = singleton1::getInstance();
	if(instance1_1 == instance1_2)
		cout<<"instance1_1 == instance1_2"<<'\n';

	singleton2 * instance2_1 = singleton2::getInstance();
	singleton2 * instance2_2 = singleton2::getInstance();
	if(instance2_1 == instance2_2)
		cout<<"instance2_1 == instance2_2"<<'\n';
	
	singleton3 * instance3_1 = singleton3::getInstance();
	singleton3 * instance3_2 = singleton3::getInstance();
	if(instance3_1 == instance3_2)
		cout<<"instance3_1 == instance3_2"<<'\n';

	instance1_1->destoryInstance(); //手动delete,instance1_1
	//instance2_1 在程序结束后会自动析构 
	//instance3_1 在程序运行结束时,系统会调用singleton3的静态成员Gc的析构函数,该析构函数会进行资源的释放

	while(1);
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值