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

单例模式-c++实现

2016-05-17 22:33 423 查看
结合前辈们的博客,写下自己写的单例模式实现,暂时没有考虑多线程情况下

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

// This is important
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;

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: