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;
}
二、懶漢模式與餓漢模式
懶漢:故名思義,不到萬不得已就不會(huì)去實(shí)例化類,也就是說在第一次用到類實(shí)例的時(shí)候才會(huì)去實(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)文章
VC++獲得當(dāng)前進(jìn)程運(yùn)行目錄的方法
這篇文章主要介紹了VC++獲得當(dāng)前進(jìn)程運(yùn)行目錄的方法,可通過系統(tǒng)函數(shù)實(shí)現(xiàn)該功能,是非常實(shí)用的技巧,需要的朋友可以參考下2014-10-10
C語言實(shí)現(xiàn)二叉樹鏈?zhǔn)浇Y(jié)構(gòu)的示例詳解
這篇文章主要為大家詳細(xì)介紹了C語言實(shí)現(xiàn)二叉樹鏈?zhǔn)浇Y(jié)構(gòu)的相關(guān)資料,文中的示例代碼講解詳細(xì),對我們學(xué)習(xí)C語言有一定的幫助,需要的可以參考一下2022-11-11
詳解C語言中freopen()函數(shù)和fclose()函數(shù)的用法
這篇文章主要介紹了詳解C語言中freopen()函數(shù)和fclose()函數(shù)的用法,是C語言入門學(xué)習(xí)中的基礎(chǔ)知識(shí),需要的朋友可以參考下2015-08-08
C語言函數(shù)調(diào)用底層實(shí)現(xiàn)原理分析
這篇文章主要介紹了C語言函數(shù)調(diào)用底層實(shí)現(xiàn)原理,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-02-02

