其思路如下图:
//实现Singleton(单例)模式
//只能生成该类的一个实例
#include<iostream>
using namespace std;
#if 0
//只适用于单线程
class Singleton
{
private:
Singleton()//把构造函数设为私有,禁止其他人创建
{}
static Singleton* single;//定义一个静态实例,在需要的时候创建该实例
public:
static Singleton* getIntance()
{
if(single == NULL)//没有对象生成
{
single = new Singleton();
}
return single;
}
void Show()
{
cout << "Singleton1" << endl;
}
};
Singleton* Singleton::single = NULL;//静态成员变量在类外进行初始化
#endif
class Singleton
{
private:
Singleton(){}
Singleton(const Singleton&){}
static Singleton& single;
public:
static Singleton& getIntance()
{
static Singleton gsingle;//只初始化一次,在进入main函数之前已经初始化
return gsingle;
}
void Show()
{
cout << "Singleton2" << endl;
}
};
Singleton& Singleton::single = getIntance();
int main()
{
//Singleton* single1 = Singleton::getIntance();
//(*single1).Show();
Singleton& single1 = Singleton::getIntance();
single1.Show();
return 0;
}