单例模式(Singleton)——懒汉、饿汉模式

其他文章:https://blog.csdn.net/leikun153/article/details/80583009
https://www.cnblogs.com/cthon/p/9196664.html
https://blog.csdn.net/zwt0112/article/details/82720645

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

#if 0

单例模式指一个类只允许有一个实例,并提供一个访问它的全局访问点,使得系统中只有唯一的
一个对象实例,类型分为懒汉模式和饿汉模式

应用:常用于管理资源,如日志、线程池

实现方法:构造函数声明为private或protect防止被外部函数实例化,
内部保存一个private static的类指针保存唯一的实例,实例的动作由一
个public的类方法代劳,该方法也返回单例类唯一的实例

#endif

std::mutex mt;

//懒汉模式  用到的时候才去初始化
class singleton
{
protected:
	singleton() {}
private:
	//俩个禁止可加可不加
	singleton(const singleton&) {};  //禁止拷贝
	singleton& operator=(const singleton&) {};  //禁止赋值
	static singleton* m_pInstance;
public:
	static singleton* GetInstance();
};
singleton* singleton::m_pInstance = NULL;

singleton* singleton::GetInstance()
{
	if (m_pInstance == nullptr)
	{
		mt.lock();
	    m_pInstance = new singleton;
		mt.unlock();
	}
	return m_pInstance;
}

//饿汉模式	单例类定义的时候就进行初始化
//因为定义时就已经初始化完成,所以多线程环境下,线程是安全的
class singleton
{
protected:
	singleton() {}
private:
	//俩个禁止可加可不加
	singleton(const singleton&) {};  //禁止拷贝
	singleton& operator=(const singleton&) {};  //禁止赋值
	static singleton* m_pInstance;
public:
	static singleton* GetInstance();
};
singleton* singleton::m_pInstance = new singleton;
singleton* singleton::GetInstance()
{
	return m_pInstance;
}

int main()
{
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值