实现Singleton(单例)模式

其思路如下图:


//实现Singleton(单例)模式
//只能生成该类的一个实例
#include<iostream>
using namespace std;

#if 0
//只适用于单线程
class Singleton
{
private:
	Singleton()//把构造函数设为私有,禁止其他人创建
	{}
	static Singleton* single;//定义一个静态实例,在需要的时候创建该实例
public:
	static Singleton* getIntance()
	{
		if(single == NULL)//没有对象生成
		{
			single = new Singleton();
		}
		return single;
	}
	void Show()
	{
		cout << "Singleton1" << endl;
	}
};
Singleton* Singleton::single = NULL;//静态成员变量在类外进行初始化
#endif

class Singleton
{
private:
	Singleton(){}
	Singleton(const Singleton&){}
	static Singleton& single;
public:
	static Singleton& getIntance()
	{
		static Singleton gsingle;//只初始化一次,在进入main函数之前已经初始化
		return gsingle;
	}
	void Show()
	{
		cout << "Singleton2" << endl;
	}
};

Singleton& Singleton::single = getIntance();

int main()
{
	//Singleton* single1 = Singleton::getIntance();
	//(*single1).Show();

	Singleton& single1 = Singleton::getIntance();
	single1.Show();

	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值