您好,登錄后才能下訂單哦!
單例模式:全局唯一實(shí)例,提供一個(gè)很容易獲取這個(gè)實(shí)例的接口
線程安全的單例:
懶漢模式(Lazy Loading):第一次獲取對(duì)象時(shí)才創(chuàng)建對(duì)象
class Singleton { public: //獲取唯一實(shí)例的接口函數(shù) static Singleton* GetInstance() { //雙重檢查,提高效率,避免高并發(fā)場(chǎng)景下每次獲取實(shí)例對(duì)象都進(jìn)行加鎖 if (_sInstance == NULL) { std::lock_guard<std::mutex> lock(_mtx); if (_sInstance == NULL) { Singleton* tmp = new Singleton; MemoryBarrier(); //內(nèi)存柵欄,防止編譯器優(yōu)化 _sInstance = tmp; } } return _sInstance; } static void DelInstance() { if (_sInstance) { delete _sInstance; _sInstance = NULL; } } void Print() { std::cout << _data << std::endl; } private: //構(gòu)造函數(shù)定義為私有,限制只能在類內(nèi)實(shí)例化對(duì)象 Singleton() :_data(10) {} //防拷貝 Singleton(const Singleton&); Singleton& operator=(const Singleton&); private: static std::mutex _mtx; //保證線程安全的互斥鎖 static Singleton* _sInstance; //指向?qū)嵗闹羔樁x為靜態(tài)私有,這樣定義靜態(tài)成員獲取對(duì)象實(shí)例 int _data; //單例類里面的數(shù)據(jù) };
餓漢模式(Eager Loading):第一次獲取對(duì)象時(shí),對(duì)象已經(jīng)創(chuàng)建好。
簡(jiǎn)潔、高效、不用加鎖,但是在某些場(chǎng)景下會(huì)有缺陷。
/*方式一*/ class Singleton { public: static Singleton* GetInstance() { static Singleton sInstance; return &sInstance; } void Print() { std::cout << _data << std::endl; } private: Singleton() :_data(10) {} Singleton(const Singleton&); Singleton& operator=(const Singleton&); private: static Singleton* _sInstance; int _data; }; void TestSingleton() { Singleton::GetInstance()->Print(); }
/*方式二*/ class Singleton { public: static Singleton* GetInstance() { static Singleton sInstance; return &sInstance; } static void DelInstance() { if (_sInstance) { delete _sInstance; _sInstance = NULL; } } void Print() { std::cout << _data << std::endl; } private: Singleton() :_data(10) {} Singleton(const Singleton&); Singleton& operator=(const Singleton&); private: static Singleton* _sInstance; int _data; }; Singleton* Singleton::_sInstance = new Singleton; void TestSingleton() { Singleton::GetInstance()->Print(); Singleton::DelInstance(); }
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。