單例模式
確保一個類只有一個實例,並提供一個全局訪問點。
應用分析
還有一些對象其實我們只需要一個,比如說:線程池(threadpool)、緩存(cache)、對話框、處理偏好設置和註冊表的對象、日誌對象,充當打印機、顯卡等設備的驅動程序對象。事實上,這類對象只能有一個實例,如果製造出多個實例,就會導致許多問題產生,例如:程序的行爲異常、資源使用過量、或者是不一致的結果。
代碼分析
//Singleton.h
//經典的單例模式
#ifndef SINGLETON_H
#define SINGLETON_H
#include <iostream>
class Singleton
{
private:
static Singleton *uniqueInstance;//聲明一個靜態變量來記錄Singleton類的唯一實例
Singleton(){}//把構造函數聲明爲私有的,只能自Singleton類內纔可以調用它
public:
static Singleton * getInstance()//實例化對象,並返回實例,只有在需要時,才實例化
{
if(uniqueInstance==NULL)
uniqueInstance=new Singleton();
return uniqueInstance;
}
//這裏是其他的有用方法
void fun()
{
std::cout<<"Singleton Pattern"<<std::endl;
}
};
Singleton *Singleton::uniqueInstance=NULL;//定義uniqueInstance,分配空間
#endif
//Main.cpp
//測試程序
#include "Singleton.h"
int main()
{
Singleton *s=Singleton::getInstance();
s->fun();
return 0;
}
模式分析——模式問題:多線程處理中,仍有可能造成實例化多個對象的情況,如第一次調用getInstance時,在if判斷之後中斷。
解決方案:
1.使用同步鎖,如果getInstance的性能對應用程序不是很關鍵的話——設置uniqueSingleton爲同步變量
2.使用“急切”創建實例,而不用延遲實例化的做法
Singleton *Singleton::uniqueInstance=new Singleton();//定義uniqueInstance時,直接創建實例
3.用“雙重檢查加鎖”,在getInstance中減少同步使用
static Singleton * getInstance()//實例化對象,並返回實例,只有在需要時,才實例化
{
if(uniqueInstance==NULL)
{
//在此加鎖
if(uniqueInstance==NULL)
uniqueInstance=new Singleton();
}
return uniqueInstance;
}