单例模式(饿汉模式和懒汉模式实现)

单例模式

单例模式的概念

一个类智能创建一个对象,单例模式可以保证系统中该类只有一个实例,并提供一个访问他的全局访问点,该实例被所有程序模块共享

饿汉模式

不管用不用,程序启东时就创建一个唯一的实例对象

优点:简单
缺点:可能会导致进程启动慢,且如果有多个单例模式对象实例启动顺序不确定

#include <iostream>

using namespace std;

class Singleton
{
public:
	static Singleton* GetInstance()
	{
		return &m_instance;
	}
private:
	//构造函数私有
	Singleton()
	{

	}

	//C++98防拷贝
	Singleton(const Singleton&);
	Singleton& operator=(Singleton const&);

	//C++11防止拷贝
	Singleton(const Singleton&) = delete;
	Singleton& operator=(Singleton const&) = delete;

	static Singleton m_instance;
};

Singleton Singleton::m_instance;//在程序入口之前就完成单利对象的初始化

int main()
{

	system("pause");
	return 0;
}

懒汉模式

延迟加载

优点:第一次使用实例对象时,创建对象,进程启动无负载,多个单例实例启动顺序自由控制
缺点:复杂

#include <iostream>
#include <mutex>
#include <thread>

using namespace std;

class Singleton
{
public:
	static Singleton* GetInstance()
	{
		if (m_pInstance == nullptr)
		{
			m_mutex.lock();
			if (m_pInstance == nullptr)
			{
				m_pInstance = new Singleton();
			}
			m_mutex.unlock();
		}
		return m_pInstance;
	}

	//实现一个内嵌垃圾回收类
	class CGarbo
	{
	public:
		~CGarbo()
		{
			if (Singleton::m_pInstance)
			{
				delete Singleton::m_pInstance;
			}
		}
	public:
		//定义一个静态成员变量,程序结束时,系统会自动调用它的析构函数从而释放单例对象
		static CGarbo Garbo;
	};

private:
	//构造函数
	Singleton()
	{

	}

	//C++98防拷贝
	Singleton(const Singleton&);
	Singleton& operator=(Singleton const&);
	
	C++11防止拷贝
	//Singleton(const Singleton&) = delete;
	//Singleton& operator=(Singleton const&) = delete;

	static Singleton* m_pInstance;//单例对象指针
	static mutex m_mutex;//互斥锁

};

Singleton* Singleton::m_pInstance = nullptr;
Singleton::CGarbo Garbo;
mutex Singleton::m_mutex;

void Func(int n)
{
	cout << Singleton::GetInstance() << endl;
}

int main()
{

	thread t1(Func, 10);
	thread t2(Func, 10);

	t1.join();
	t2.join();

	cout << Singleton::GetInstance() << endl;
	cout << Singleton::GetInstance() << endl;

	system("pause");
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值