日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

c++实现单例类(懒汉与饿汉)

發(fā)布時間:2024/4/11 c/c++ 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 c++实现单例类(懒汉与饿汉) 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

教科書里的單例模式

  我們都很清楚一個簡單的單例模式該怎樣去實現(xiàn):構造函數聲明為private或protect防止被外部函數實例化,內部保存一個private static的類指針保存唯一的實例,實例的動作由一個public的類方法代勞,該方法也返回單例類唯一的實例。

  上代碼:  

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 class?singleton { protected: ????singleton(){} private: ????static?singleton* p; public: ????static?singleton* instance(); }; singleton* singleton::p = NULL; singleton* singleton::instance() { ????if?(p == NULL) ????????p =?new?singleton(); ????return?p; }

?懶漢與餓漢

  單例大約有兩種實現(xiàn)方法:懶漢與餓漢。

    • 懶漢:故名思義,不到萬不得已就不會去實例化類,也就是說在第一次用到類實例的時候才會去實例化,所以上邊的經典方法被歸為懶漢實現(xiàn);
    • 餓漢:餓了肯定要饑不擇食。所以在單例類定義的時候就進行實例化。

  特點與選擇:

    • 由于要進行線程同步,所以在訪問量比較大,或者可能訪問的線程比較多時,采用餓漢實現(xiàn),可以實現(xiàn)更好的性能。這是以空間換時間。
    • 在訪問量較小時,采用懶漢實現(xiàn)。這是以時間換空間。

3 線程安全的懶漢實現(xiàn)

  線程不安全,怎么辦呢?最直觀的方法:加鎖。

#include<iostream>
using namespace std;


class single
{
protected:
single()
{}
private:
static single *s;
public:
static single* instant();?
};
single* single::s=NULL;
single* single::instant()
{
if(s==NULL)
{
s=new single();
}
return s;
}






//懶漢加鎖s實現(xiàn)
class single
{
protected:
single()
{
pthread_mutex_initI(&mutex);
}
private:
static single *s;
static pthread_mutex_t mutex;
public:
static single* instant();?
};
pthread_mutex_t single::mutex;
single* single::s=NULL;
single* single::instant()
{
if(p==NULL)
{
pthread_mutex_lock(&mutex);
if(s==NULL)
{
s=new single();
}
pthread_mutex_unlock(&mutex);
}
return s;
}
//n內部靜態(tài)變量的懶漢實現(xiàn)
class single
{
protected:
single()
{
pthread_mutex_init(&mutex);
}
private:
static int a;
static pthread_mutex_t mutex;
static single* instant();?
};
pthread_mutex_t single::mutex;
single* single::instant()
{
pthread_mutex_lock(&mutex);
static single obj;
pthread_mutex_unlock(&mutex);
return &obj;
}
//e餓漢實現(xiàn)-》線程安全
class single
{
protected:
single()
{}
private:
static single *s;
public:
static single* instant();?
};
single* single::s=new single();
single* single::instant()
{
return s;
}


超強干貨來襲 云風專訪:近40年碼齡,通宵達旦的技術人生

總結

以上是生活随笔為你收集整理的c++实现单例类(懒汉与饿汉)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。