C++實現(xiàn) 單例模式實例詳解
設(shè)計模式之單例模式C++實現(xiàn)
一、經(jīng)典實現(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;
}
二、懶漢模式與餓漢模式
懶漢:故名思義,不到萬不得已就不會去實例化類,也就是說在第一次用到類實例的時候才會去實例化,所以上邊的經(jīng)典方法被歸為懶漢實現(xiàn);
餓漢:餓了肯定要饑不擇食。所以在單例類定義的時候就進行實例化。
特點與選擇
由于要進行線程同步,所以在訪問量比較大,或者可能訪問的線程比較多時,采用餓漢實現(xiàn),可以實現(xiàn)更好的性能。這是以空間換時間。在訪問量較小時,采用懶漢實現(xiàn)。這是以時間換空間。
線程安全的懶漢模式
1.加鎖實現(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)變量實現(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語言實現(xiàn)二叉樹鏈式結(jié)構(gòu)的示例詳解
這篇文章主要為大家詳細介紹了C語言實現(xiàn)二叉樹鏈式結(jié)構(gòu)的相關(guān)資料,文中的示例代碼講解詳細,對我們學習C語言有一定的幫助,需要的可以參考一下2022-11-11
詳解C語言中freopen()函數(shù)和fclose()函數(shù)的用法
這篇文章主要介紹了詳解C語言中freopen()函數(shù)和fclose()函數(shù)的用法,是C語言入門學習中的基礎(chǔ)知識,需要的朋友可以參考下2015-08-08
C語言函數(shù)調(diào)用底層實現(xiàn)原理分析
這篇文章主要介紹了C語言函數(shù)調(diào)用底層實現(xiàn)原理,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-02-02

