转:C++实现单例模式
http://cppentry.com/bencandy.php?fid=49&aid=1112
?
单例模式:Singleton?单例模式确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例单例模式。单例模式只应在有真正的“单一实例”的需求时才可使用。
我实现了一个简单的单例类,欢迎吐槽。
#include<iostream>
using?namespace?std;
class?Singleton
{
public:
????static?Singleton?*?GetInstance()//通过静态公有函数获得该类的实例对象
????{
????????if(m_pInstance==NULL)
????????m_pInstance=new?Singleton();
????????return?m_pInstance;
????}
private:
????Singleton(){}//构造函数私有化的目的是为了防止从别处实例化该类对象
????static?Singleton?*?m_pInstance;
????class?Garbo//删除Singleton实例的对象
????{
????public:
????????~Garbo()
????????{
????????????if(Singleton::m_pInstance)
????????????{
????????????????delete?Singleton::m_pInstance;
????????????}
????????}
????};
????static?Garbo?gb;//在程序结束时,系统会调用它的析构函数
};
Singleton?*?Singleton::m_pInstance=NULL;//初始化静态数据成员
int?main()
{
????Singleton?*sl=Singleton::GetInstance();
????return?0;
}
