#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);
}