#include <iostream>
using namespace std;
class Singleton
{
public:
static Singleton *GetInstance()
{
if (m_Instance == NULL )
{
Lock(); // C++没有直接的Lock操作,请使用其它库的Lock,比如Boost,此处仅为了说明
if (m_Instance == NULL )
{
m_Instance = new Singleton ();
}
UnLock(); // C++没有直接的Lock操作,请使用其它库的Lock,比如Boost,此处仅为了说明
}
return m_Instance;
}
static void DestoryInstance()
{
if (m_Instance != NULL )
{
delete m_Instance;
m_Instance = NULL ;
}
}
int GetTest()
{
return m_Test;
}
private:
Singleton(){ m_Test = 0; }
static Singleton *m_Instance;
int m_Test;
};
Singleton *Singleton ::m_Instance = NULL;
int main(int argc , char *argv [])
{
Singleton *singletonObj = Singleton ::GetInstance();
cout<<singletonObj->GetTest()<<endl;
Singleton ::DestoryInstance();
return 0;
}
此处进行了两次m_Instance == NULL的判断,是借鉴了Java的单例模式实现时,使用的所谓的“双检锁”机制。因为进行一次加锁和解锁是需要付出对应的代价的,而进行两次判断,就可以避免多次加锁与解锁操作,同时也保证了线程安全。但是,这种实现方法在平时的项目开发中用的很好,也没有什么问题?但是,如果进行大数据的操作,加锁操作将成为一个性能的瓶颈;
#include <iostream>
using namespace std;
class Singleton
{
public:
static Singleton *GetInstance()
{
return const_cast <Singleton *>(m_Instance);
}
static void DestoryInstance()
{
if (m_Instance != NULL )
{
delete m_Instance;
m_Instance = NULL ;
}
}
int GetTest()
{
return m_Test;
}
private:
Singleton(){ m_Test = 10; }
static const Singleton *m_Instance;
int m_Test;
};
const Singleton *Singleton ::m_Instance = new Singleton();
int main(int argc , char *argv [])
{
Singleton *singletonObj = Singleton ::GetInstance();
cout<<singletonObj->GetTest()<<endl;
Singleton ::DestoryInstance();
}
因为静态初始化在程序开始时,也就是进入主函数之前,由主线程以单线程方式完成了初始化,所以静态初始化实例保证了线程安全性。在性能要求比较高时,就可以使用这种方式,从而避免频繁的加锁和解锁造成的资源浪费。
#include <iostream>
using namespace std;
class Singleton
{
public:
static Singleton *GetInstance()
{
static Singleton m_Instance;
return &m_Instance;
}
int GetTest()
{
return m_Test++;
}
private:
Singleton(){ m_Test = 10; };
int m_Test;
};
int main(int argc , char *argv [])
{
Singleton *singletonObj = Singleton ::GetInstance();
cout<<singletonObj->GetTest()<<endl;
singletonObj = Singleton ::GetInstance();
cout<<singletonObj->GetTest()<<endl;
}
转载:https://www.cnblogs.com/wuchanming/p/4486357.html