定义:单例模式(Singleton),保证一个类仅有一个实例,并提供一个访问它的全局访问点。【DP】
UML:
源码:
// Singleton.cpp
#include <iostream>
using namespace std;
#define OS_IS_WINDOWS
#if defined(OS_IS_WINDOWS)
#include <windows.h>
CRITICAL_SECTION g_cs;
#endif
#if defined(OS_IS_LINUX)
#include <pthread.h>
pthread_mutex_t g_mutex;
#endif
class Singleton
{
private:
static Singleton *instance;
private:
Singleton(){}//构造函数私有化,防止直接实例化对象,否则实例化的个数就无法控制了
public:
static Singleton *GetInstance()
{
if (!instance)
{
#if defined(OS_IS_LINUX)
pthread_mutex_lock(&g_mutex);
if (!instance)
{
instance = new Singleton;
}
pthread_mutex_unlock(&g_mutex);
#endif
#if defined(OS_IS_WINDOWS)
EnterCriticalSection(&g_cs);
if (!instance)
{
instance = new Singleton;
}
LeaveCriticalSection(&g_cs);
#endif
}
return instance;
}
//销毁单例(或者进程中会一直保存这个单例,知道进程退出,自动销毁,那么次方法就没有实际用处了)
void DestoryInstance()
{
#if defined(OS_IS_LINUX)
pthread_mutex_destroy(&g_mutex);
#endif
#if defined(OS_IS_WINDOWS)
DeleteCriticalSection(&g_cs);
#endif
delete instance;
instance = 0;//这句非常关键,因为删除一次后就已经野指针了
}
};
Singleton *Singleton::instance = 0;//需要对静态成员变量外部初始化,否则连接失败
int main()
{
#if defined(OS_IS_WINDOWS)
InitializeCriticalSection(&g_cs);
#endif
#if defined(OS_IS_LINUX)
pthread_mutex_init(&g_mutex, NULL);
#endif
Singleton *instance1 = Singleton::GetInstance();
Singleton *instance2 = Singleton::GetInstance();
if (instance1 == instance2)
{
cout << "两个实例相同,实际上是一个实例" << endl;
}
instance1->DestoryInstance();
instance2->DestoryInstance();//实际上删除一次就够了
return 0;
}
输出:
这里兼容了windows和linux两个平台,我只是简单的采用一组宏来解决,实际做项目时,可以将互斥量在抽象下,封装成一个类,提供实例化,lock和unlock方法。
为了考虑多线程使用情况,这里使用了线程互斥,但是为什么需要两个if呢?
两个if的原因,也叫做双重锁定:
1.第一个if对instance存在的情况,直接放回,这里没有问题;
2.当instance为空,并且同时有两个线程调用GetInstance时,使用锁可以保证只有一个能进入,另一个在锁外面等候;
3.如果没有里面的if(也就是第二个if),一旦前面的线程已经创建了,此时等候的线程再进入创建,就会重复创建了。
所以,多线程的情况一定要锱铢必较!!!
优点:单例模式因为Singleton类封装它的唯一实例,这样它可以严格地控制客户怎样访问它以及何时访问它。简单地说就是对唯一实例的受控访问。