C++實(shí)現(xiàn) 單例模式實(shí)例詳解
設(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++基于Floyd算法實(shí)現(xiàn)校園導(dǎo)航系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了C++基于Floyd算法實(shí)現(xiàn)校園導(dǎo)航系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-03-03MFC創(chuàng)建模態(tài)對話框和非模態(tài)對話框的方法
這篇文章主要介紹了MFC創(chuàng)建模態(tài)對話框和非模態(tài)對話框的方法,需要的朋友可以參考下2014-07-07C語言中g(shù)etchar函數(shù)詳解看這一篇就夠了(函數(shù)功能、使用、返回值)
getchar讀取字符的函數(shù),今天通過本文給大家介紹C語言中g(shù)etchar函數(shù)簡介用法示例詳解,感興趣的朋友跟隨小編一起看看吧2023-02-02C++?OpenGL實(shí)現(xiàn)旋轉(zhuǎn)立方體的繪制
這篇文章主要主要為大家詳細(xì)介紹了如何利用C++和OpenGL實(shí)現(xiàn)旋轉(zhuǎn)立方體的繪制,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起動手嘗試一下2022-07-07

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

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