2种单例模式类型

#include <iostream>
using namespace std;

//单例模式全局只能有一个对象,注意:懒汉模式遇到多线程 需要创建一个互斥锁,使它线性执行


//懒汉
class Singelton {
public:
	static Singelton* getInstance() {
		//
		if (NULL == instance)
		{
			  instance = new Singelton;
		}
		//
		++m_count;
		
		return instance;
	}

	void show_count()
	{
		cout << m_count << endl;
	}
private:
	Singelton() {
		
		instance = NULL;
		m_count = 0;
		cout << "懒汉模式" << endl;
	}
public:
	static Singelton* instance;
	static int m_count;
};

int Singelton::m_count = 0;
Singelton* Singelton::instance = NULL;


//饿汉
class Singelton1 {
public:
	static Singelton1* getInstance() {
		++m_count;
		return instance;
	}

	void show_count()
	{
		cout << m_count << endl;
	}
private:
	Singelton1() {

		instance = NULL;
		m_count = 0;
		cout << "饿汉模式" << endl;
	}
public:
	static Singelton1* instance;
	static int m_count;
};

int Singelton1::m_count = 0;
Singelton1* Singelton1::instance = new Singelton1;

int main()
{
	Singelton* sp1 = Singelton::getInstance();
	Singelton* sp2 = Singelton::getInstance();

	if(sp1 == sp2)
	{ 
		cout << "懒汉相同" << endl;
	}
	else
	{
		cout << "懒汉不相同" << endl;
	}
	sp2->show_count();


	Singelton1* sp3 = Singelton1::getInstance();
	Singelton1* sp4 = Singelton1::getInstance();
	
	
	if (sp3 == sp4)
	{
		cout << "饿汉相同" << endl;
	}
	else
	{
		cout << "饿汉不相同" << endl;
	}
	sp4->show_count();

	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱写代码的马良

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值