关于单利模式的实现,网上的博客很多,考虑到线程安全,以空间换时间等等,这里我给出单利模式最简单多线程全的实现,代码如下:
#include <iostream>
using namespace std;
class Singleton
{
public:
static Singleton *GetInstance()
{
return m_Instance;
}
int GetTest()
{
return m_Test;
}
private:
Singleton() { m_Test = 10; }
static Singleton *m_Instance;
int m_Test;
//用内部类销毁单例
class GC
{
public:
~GC()
{
// We can destory all the resouce here, eg:db connector, file handle and so on
if (m_Instance != NULL)
{
cout << "Here is the test" << endl;
delete m_Instance;
m_Instance = NULL;
}
}
};
static GC gc;
};
Singleton *Singleton::m_Instance = new Singleton();
Singleton::GC Singleton::gc; //全局对象,程序结束时会掉用它的析构函数
int main(int argc, char *argv[])
{
Singleton *singletonObj = Singleton::GetInstance();
cout << singletonObj->GetTest() << endl;
system("pause");
return 0;
}
在程序运行结束时,系统会调用Singleton的静态成员GC的析构函数,该析构函数会进行资源的释放,而这种资源的释放方式是在程序员“不知道”的情况下进行的,而程序员不用特别的去关心,使用单例模式的代码时,不必关心资源的释放。那么这种实现方式的原理是什么呢?我剖析问题时,喜欢剖析到问题的根上去,绝不糊涂的停留在表面。由于程序在结束的时候,系统会自动析构所有的全局变量,实际上,系统也会析构所有类的静态成员变量,就像这些静态变量是全局变量一样。我们知道,静态变量和全局变量在内存中,都是存储在静态存储区的,所以在析构时,是同等对待的。
由于此处使用了一个内部 GC 类,而该类的作用就是用来释放资源,而这种使用技巧在 C++ 中是广泛存在的。