单例模式:保证一个类仅有一个实例,并且提供一个访问它的全局访问点。即让类本身负责保存它的唯一样例。
代码实现思路:在类内定义一个私有的静态实例,并且将构造函数也定义为私有,然后定义一个共有的静态方法来获取实例,作为唯一全局访问点。
代码:
#include<iostream>
using namespace std;
class Singleton
{
private:
static Singleton*instance;
Singleton() //私有构造函数
{
}
public:
static Singleton* GetInstance() //唯一的全局访问点
{
if (instance == NULL)
{
instance = new Singleton();
}
return instance;
}
};
Singleton* Singleton::instance = NULL;
int main()
{
Singleton*instance0 = Singleton::GetInstance();
Singleton*instance1 = Singleton::GetInstance();
if (instance0 == instance1)
{
cout << "两个指针指向同一个实例"<<endl;
}
return 0;
}
加入线程安全的GetInstance函数:
CRITICAL_SECTION console;
//适合多线程的GetInstance()多线程
static Singleton* GetInstance()
{
if (instance == NULL)
{
EnterCriticalSection(&console);
if (instance==NULL)
instance = new Singleton();
LeaveCriticalSection(&console);
}
return instance;
}