1.C++语言实现单例模方法一
class Singleton{
private:
static Singleton* single;
Singleton(){cout<<"construct of Singleton"<<endl;}
public:
static Singleton& getInstance()
{
if(single==NULL)
single=new Singleton();
return *single;
}
class CGarbage
{
public:
CGarbage(){cout<<"construct of CGarbage"<<endl;}
~CGarbage()
{
if(single!=NULL)
delete single;
cout<<"delete single"<<endl;
}
};
private:
static CGarbage cg;
};
Singleton* Singleton::single=NULL;
Singleton::CGarbage Singleton::cg;
int main()
{
Singleton::getInstance();
return 0;
}
2.C++语言实现单例模式方法二
class Singleton
{
private:
Singleton(){cout<<"construct of Singleton"<<endl;}
public:
static Singleton& getInstance()
{
static Singleton single;
return single;
}
};
3.C++语言实现单例模式方法三
class Singleton{ private: static Singleton single; Singleton(){cout<<"construct of Singleton"<<endl;} public: static Singleton& getInstance() { return single; } ~Singleton() { cout<<"destruct of Singleton"<<endl; } }; Singleton Singleton::single;