單例模式(Singleton),保證一個(gè)類(lèi)僅有一個(gè)實(shí)例,并提供一個(gè)訪問(wèn)它的全局訪問(wèn)點(diǎn)。其構(gòu)造過(guò)程由自身完成,可以將構(gòu)造方法定義為private型的,這樣外界就只能通過(guò)定義的靜態(tài)的函數(shù)Instance()構(gòu)造實(shí)例,這個(gè)函數(shù)的目的就是返回一個(gè)類(lèi)的實(shí)例,在此方法中去做是否有實(shí)例化的判斷。客戶端不再考慮是否需要去實(shí)例化的問(wèn)題,把這些都交給了單例類(lèi)自身。通常我們可以讓一個(gè)全局變量使得一個(gè)對(duì)象被訪問(wèn),但它不能防止你實(shí)例化多個(gè)對(duì)象。一個(gè)最好的辦法,就是讓類(lèi)自身負(fù)責(zé)保存它的唯一實(shí)例。這個(gè)類(lèi)可以保證沒(méi)有其他實(shí)例可以被創(chuàng)建,并且它可以提供一個(gè)訪問(wèn)該實(shí)例的方法。
C++版本:
template <class T> class Singleton { public: static inline T* Instance(); static inline void ReleaseInstance(); private: Singleton(void){} ~Singleton(void){} Singleton(const Singleton&){} Singleton & operator= (const Singleton &){} static std::auto_ptr<T> m_instance; static ThreadSection m_critSection; }; template <class T> std::auto_ptr<T> Singleton<T>::m_instance; template <class T> ThreadSection Singleton<T>::m_critSection; template <class T> inline T* Singleton<T>::Instance() { AutoThreadSection aSection(&m_critSection); if( NULL == m_instance.get()) { m_instance.reset ( new T); } return m_instance.get(); } template<class T> inline void Singleton<T>::ReleaseInstance() { AutoThreadSection aSection(&m_critSection); m_instance.reset(); }#define DECLARE_SINGLETON_CLASS( type ) / friend class std::auto_ptr< type >;/ friend class Singleton< type >;
多線程時(shí)Instance()方法加鎖保護(hù),防止多線程同時(shí)進(jìn)入創(chuàng)建多個(gè)實(shí)例。m_instance為auto_ptr指針類(lèi)型,有g(shù)et和reset方法。發(fā)現(xiàn)好多網(wǎng)上的程序沒(méi)有對(duì)多線程進(jìn)行處理,筆者覺(jué)得這樣問(wèn)題很大,因?yàn)槿绻粚?duì)多線程處理,那么多線程使用時(shí)就可能會(huì)生成多個(gè)實(shí)例,違背了單例模式存在的意義。加鎖保護(hù)就意味著這段程序在絕大部分情況下,運(yùn)行是沒(méi)有問(wèn)題的,這也就是筆者對(duì)自己寫(xiě)程序的要求,即如果提前預(yù)料到程序可能會(huì)因?yàn)槟硞€(gè)地方?jīng)]處理好而出問(wèn)題,那么立即解決它;如果程序還是出問(wèn)題了,那么一定是因?yàn)槟硞€(gè)地方超出了我們的認(rèn)知。
再附一下Java版的單例模式:
public class Singleton { private Singleton() { } private static Singleton single = null; public static Singleton getInstance() { if (single == null) { synchronized (Singleton.class) { if (single == null) { single = new Singleton(); } } } return single; }}
上述代碼中,一是對(duì)多線程做了處理,二是采用了雙重加鎖機(jī)制。由于synchronized每次都會(huì)獲取鎖,如果沒(méi)有最外層的if (single == null)的判斷,那么每次getInstance都必須獲取鎖,這樣會(huì)導(dǎo)致性能下降,有了此判斷,當(dāng)生成實(shí)例后,就不會(huì)再獲取鎖。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持VEVB武林網(wǎng)。
新聞熱點(diǎn)
疑難解答