【C++设计模式】单例模式

 

#ifndef __SINGLETON_H__
#define __SINGLETON_H__

#include <mutex>

//单例模式
//定义:保证一个类仅有一个实例,并提供一个访问它的全局访问点,该实例被所有程序模块共享。
//构造函数和赋值运算符定义为私有,防止外部用户构造类的对象,用户只能通过Instance函数获取对象。
//需要注意多线程访问的安全性。


class Singleton
{
private:
	Singleton(){ };
	Singleton(const Singleton&){ };
	Singleton& operator = (const Singleton &) { };

public:

	static Singleton* Instance();

	void   SetValue(int value);

private:	
	static Singleton * m_instance;
	static std::mutex m_mtx;
	int    m_value;

};

void TestSingleton();

#endif

#include "Singleton.h"

Singleton * Singleton::m_instance = 0;
std::mutex  Singleton::m_mtx;

Singleton* Singleton::Instance()
{
	if (NULL == m_instance)
	{
		m_mtx.lock();			//用lock实现线程安全
		if (NULL == m_instance)
		{
			static Singleton instance;
			m_instance = &instance;
		}
		m_mtx.unlock();
	}

	return m_instance;
}

void Singleton::SetValue(int value)
{
	m_value = value;
}

void TestSingleton()
{
	Singleton * instance = Singleton::Instance();

	instance->SetValue(2);	
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值