1. 程式人生 > >C++實現一個單例模式(懶漢與餓漢)

C++實現一個單例模式(懶漢與餓漢)

單例模式的特點:
1、一個類只能有一個例項。
2、一個類必須自己建立自己的唯一例項。
3、一個類必須給所有其他物件提供這一例項。

單例模式的實現:
1、將建構函式宣告為private防止被外部函式例項化;
2、包含一個靜態私有類指標sig和靜態公有方法instance();
3、instance方法負責檢驗並例項化自己,然後儲存在靜態類指標sig中,以確保只有一個例項被建立。

參考程式碼

class singleton
{
    //建構函式宣告為私有的
private:
    singleton()
    {}
    //靜態私有類指標
private:
    static
singleton *sig; //靜態公有方法 public: static singleton* instance() { if (sig == NULL) sig = new singleton(); return sig; } };

如上方法是執行緒不安全的,如果兩個執行緒同時首次呼叫instance方法且同時檢測到p是NULL值,則兩個執行緒會同時構造一個例項給p,這樣是錯誤的。

餓漢模式與懶漢模式

懶漢:在第一次用到類例項的時候才會去例項化,所以上邊的方法被歸為懶漢實現。

餓漢:餓了肯定要飢不擇食。所以在單例類定義的時候就進行例項化。

優缺點:

訪問量比較大,或者可能訪問的執行緒比較多時,採用餓漢實現,以空間換時間。
訪問量較小時,採用懶漢實現。以時間換空間。

執行緒安全的懶漢實現:

1、加鎖

class singleton
{
private:
    singleton()
    {
    pthread_mutex_init(&lock);
    }
private:
    static singleton *sig;
    static pthread_mutex_t lock;
public:
    static singleton* instance()
    {
        if
(sig == NULL) { pthread_mutex_lock(&lock); if (sig == NULL) sig = new singleton(); pthread_mutex_unlock(&lock); } return sig; } };

2、內部靜態變數

class singleton
{
private:
    singleton()
    {
    pthread_mutex_init(&lock);
    }
public:
    static pthread_mutex_t lock;
    int p;
public:
    static singleton* instance()
    {
        pthread_mutex_lock(&lock);
        static singleton sig;
        pthread_mutex_unlock(&lock);
        }
        return &sig;
    }
};

餓漢的實現
在instance函式裡定義一個靜態的例項,也可以保證擁有唯一例項,在返回時只需要返回其指標.

餓漢本身就是安全的。

class singleton
{
protected:
    singleton()
    {}
private:
    static singleton *sig;
public:
    static pthread_mutex_t lock;
public:
    sig=new singleton;
    static singleton* instance()
    {
        return sig;
    }
};