歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 設計模式之單例模式簡述

設計模式之單例模式簡述

日期:2017/3/1 9:08:35   编辑:Linux編程

單例模式(Singleton),保證一個類僅有一個實例,並提供一個訪問它的全局訪問點。其構造過程由自身完成,可以將構造方法定義為private型的,這樣外界就只能通過定義的靜態的函數Instance()構造實例,這個函數的目的就是返回一個類的實例,在此方法中去做是否有實例化的判斷。客戶端不再考慮是否需要去實例化的問題,把這些都交給了單例類自身。通常我們可以讓一個全局變量使得一個對象被訪問,但它不能防止你實例化多個對象。一個最好的辦法,就是讓類自身負責保存它的唯一實例。這個類可以保證沒有其他實例可以被創建,並且它可以提供一個訪問該實例的方法。

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 >;

多線程時Instance()方法加鎖保護,防止多線程同時進入創建多個實例。m_instance為auto_ptr指針類型,有get和reset方法。發現好多網上的程序沒有對多線程進行處理,筆者覺得這樣問題很大,因為如果不對多線程處理,那麼多線程使用時就可能會生成多個實例,違背了單例模式存在的意義。加鎖保護就意味著這段程序在絕大部分情況下,運行是沒有問題的,這也就是筆者對自己寫程序的要求,即如果提前預料到程序可能會因為某個地方沒處理好而出問題,那麼立即解決它;如果程序還是出問題了,那麼一定是因為某個地方超出了我們的認知。

再附一下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;
}
}

上述代碼中,一是對多線程做了處理,二是采用了雙重加鎖機制。由於synchronized每次都會獲取鎖,如果沒有最外層的if (single == null)的判斷,那麼每次getInstance都必須獲取鎖,這樣會導致性能下降,有了此判斷,當生成實例後,就不會再獲取鎖。

Copyright © Linux教程網 All Rights Reserved