您的位置:首页 > 编程语言 > C语言/C++

C++实现设计模式之 —— 单例模式 Singleton

2015-07-07 20:40 696 查看
单例模式是最简单的创建型模式,当某个类只需要唯一的一份实例时,使用单例模式可以确保不会创建多余的实例。在C++ 中,单例模式可以避免全局变量的使用。下面是一个典型的线程安全的单例模式

#ifndef Singleton_h__
#define Singleton_h__

#include <mutex> //C++11

class CSingleton
{
public:
static CSingleton* GetInstance()
{
if (m_pInstance == NULL)
{
m_lock.lock();
//double check for better performance
if (m_pInstance == NULL)
{
m_pInstance = new CSingleton();
}
m_lock.unlock();
}
return m_pInstance;
}

static void Destroy()
{
m_lock.lock();
delete m_pInstance;
m_pInstance = NULL;
m_lock.unlock();
}

void Method()
{
//
}
private:
CSingleton(){}
~CSingleton()
{
delete m_pInstance;
m_pInstance = NULL;
}

//Disable copy and assign
CSingleton(const CSingleton& rhs);
CSingleton& operator = (const CSingleton& rhs);

private:
static CSingleton*	m_pInstance;
static std::mutex	m_lock;
};

CSingleton* CSingleton::m_pInstance = NULL;

std::mutex CSingleton::m_lock;

#endif // Singleton_h__


为了确保线程安全,我们需要对创建实例部分进行线程加锁,上述示例代码使用了双重检查的方式,既能够确保线程安全,也避免了由于每次加锁导致的性能消耗。如果使用下面的实现方式:

static CSingleton* GetInstance()
{
m_lock.lock();
if (m_pInstance == NULL)
{
m_pInstance = new CSingleton();
}
m_lock.unlock();
return m_pInstance;
}


则每次调用GetInstance() 都需要加锁。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: