欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C++實(shí)現(xiàn) 單例模式實(shí)例詳解

 更新時(shí)間:2017年05月06日 14:39:54   投稿:lqh  
這篇文章主要介紹了C++實(shí)現(xiàn) 單例模式實(shí)例詳解的相關(guān)資料,需要的朋友可以參考下

設(shè)計(jì)模式之單例模式C++實(shí)現(xiàn)

一、經(jīng)典實(shí)現(xiàn)(非線程安全)

class Singleton 
{ 
  public: 
    static Singleton* getInstance(); 
  protected: 
    Singleton(){} 
  private: 
    static Singleton *p; 
}; 
 
Singleton* Singleton::p = NULL; 
Singleton* Singleton::getInstance() 
{ 
  if (NULL == p) 
    p = new Singleton(); 
  return p; 
} 

二、懶漢模式與餓漢模式

懶漢:故名思義,不到萬不得已就不會去實(shí)例化類,也就是說在第一次用到類實(shí)例的時(shí)候才會去實(shí)例化,所以上邊的經(jīng)典方法被歸為懶漢實(shí)現(xiàn);

餓漢:餓了肯定要饑不擇食。所以在單例類定義的時(shí)候就進(jìn)行實(shí)例化。

特點(diǎn)與選擇

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

線程安全的懶漢模式

1.加鎖實(shí)現(xiàn)線程安全的懶漢模式

class Singleton 
{ 
  public: 
    static pthread_mutex_t mutex; 
    static Singleton* getInstance(); 
  protected: 
    Singleton() 
    { 
      pthread_mutex_init(&mutex); 
    } 
  private: 
    static Singleton* p; 
}; 
 
pthread_mutex_t Singleton::mutex; 
Singleton* Singleton::p = NULL; 
Singleton* Singleton::getInstance() 
{ 
  if (NULL == p) 
  { 
    pthread_mutex_lock(&mutex); 
    if (NULL == p) 
      p = new Singleton(); 
    pthread_mutex_unlock(&mutex); 
  } 
  return p; 
}

2.內(nèi)部靜態(tài)變量實(shí)現(xiàn)懶漢模式

class Singleton 
{ 
  public: 
  static pthread_mutex_t mutex; 
  static Singleton* getInstance(); 
  protected: 
    Singleton() 
    { 
      pthread_mutex_init(&mutex); 
    } 
}; 
 
pthread_mutex_t Singleton::mutex; 
Singleton* Singleton::getInstance() 
{ 
  pthread_mutex_lock(&mutex); 
  static singleton obj; 
  pthread_mutex_unlock(&mutex); 
  return &obj; 
} 


餓漢模式(本身就線程安全)

class Singleton 
{ 
  public: 
    static Singleton* getInstance(); 
  protected: 
    Singleton(){} 
  private: 
    static Singleton* p; 
}; 
 
Singleton* Singleton::p = new Singleton; 
Singleton* Singleton::getInstance() 
{ 
  return p; 
} 

感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!

相關(guān)文章

  • C語言中g(shù)etchar和putchar的使用方法詳解

    C語言中g(shù)etchar和putchar的使用方法詳解

    我們知道scanf函數(shù)可以從鍵盤輸入信息,而printf則可以輸出信息,同樣地,getchar和putchar也有同樣的功能,下面我來給大家介紹putchar和getchar的使用方法,需要的朋友可以參考下
    2023-08-08
  • C語言實(shí)現(xiàn)班級檔案管理系統(tǒng)課程設(shè)計(jì)

    C語言實(shí)現(xiàn)班級檔案管理系統(tǒng)課程設(shè)計(jì)

    這篇文章主要為大家詳細(xì)介紹了C語言實(shí)現(xiàn)班級檔案管理系統(tǒng)課程設(shè)計(jì),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2019-12-12
  • 詳情介紹C++之命名空間

    詳情介紹C++之命名空間

    這篇文章主要詳情介紹了C++命名空間,命名空間的出現(xiàn)就是為了解決名稱沖突問題,對此感興趣的朋友可以參考下面文章
    2021-09-09
  • 最新評論