1.設(shè)計模式是什么?

成都創(chuàng)新互聯(lián)公司長期為成百上千家客戶提供的網(wǎng)站建設(shè)服務(wù),團隊從業(yè)經(jīng)驗10年,關(guān)注不同地域、不同群體,并針對不同對象提供差異化的產(chǎn)品和服務(wù);打造開放共贏平臺,與合作伙伴共同營造健康的互聯(lián)網(wǎng)生態(tài)環(huán)境。為渝中企業(yè)提供專業(yè)的成都網(wǎng)站設(shè)計、網(wǎng)站制作、外貿(mào)營銷網(wǎng)站建設(shè),渝中網(wǎng)站改版等技術(shù)服務(wù)。擁有十余年豐富建站經(jīng)驗和眾多成功案例,為您定制開發(fā)。
設(shè)計模式其實就是前人總結(jié),代表了最佳實踐,對于軟件開發(fā)過程中對象的封裝模式,也是各種復(fù)雜問題,極好解耦性的解決方案。
-------------------------------------------------------------------------------------------
下面我們來說一下單例模式的基本概念和代碼:
單例類保證了全局只有唯一一個實例對象
單例提供獲取這個唯一實例的接口
其實就是保證一個類中出現(xiàn)對象的全局唯一性。
首先對于單例模式而言,有2種
懶漢模式:
#include<bits/stdc++.h>
#include<mutex>
using namespace std;
class singleton
{
public:
static singleton* GetInstance()
{
//使用雙重檢查,保證獲取鎖的資源不浪費
if(_instance == NULL)
{
std::lock_guard<std::mutex>lck(_mtx);
if(instance == NULL)
{
//一下解釋標(biāo)記為a
singleton *tmp = new singleton();
MemoryBarrier();//內(nèi)存柵欄。后面會進行解釋。
_instance = tmp;
}
}
return _instance;
}
static void DelInstance()
{
if(_instance != NULL)
{
delete _instance;
_instance = NULL;
}
}
private:
singleton():data(0){};
singleton(const singleton&){};
singleton& operator = (const sigleton&);
static singleton* _instance;
static mutex _mtx;
int data;
}
singleton* singleton::_instance = NULL;
mutex singleton::_mtx;其實單例模式?jīng)]有真想象的這么簡單,百度上許多說單例模式的文章都說的有些許遺漏
這里主要解釋一下內(nèi)存柵欄的概念
如果我們將a處代碼轉(zhuǎn)換為_instance = new singleton();
這在編譯器中處理為3個部分,1.分配空間,2調(diào)用構(gòu)造函數(shù),3.賦值、
但是在某些情況話,編譯器可能進行優(yōu)化進行重排,然后順序變成了1,3,2.將賦值提到了構(gòu)造函數(shù)之前。
然后設(shè)想在高并發(fā)場景中,_instance已經(jīng)進行了賦值,但是沒有調(diào)用構(gòu)造函數(shù),其他現(xiàn)場進入,直接返回_instance。一個沒有調(diào)用構(gòu)造函數(shù)的_instance,這就會出現(xiàn)錯誤
所以我們聲明一個臨時變量,然后添加一個內(nèi)存柵欄,其實就是指令順序的隔斷,不可提前。保證賦值構(gòu)造的完全調(diào)用,其實就有點類似Linux中的sigsuspend();
以上就是完善的懶漢模式。
-------------------------------------------------------------------------------------------
餓漢模式:
餓漢模式使用RAII
//1
class singleton
{
public:
static singleton* GetInstance()
{
static single sInstance;
return &sInstance;
}
private:
singleton():data(0){};
singleton(const singleton&){};
singleton& operator = (const sigleton&);
static singleton* _instance;
int data;
}
//2
class singleton
{
public:
static sington* GetInstance()
{
assert(_instance);
return _instance;
}
private:
singleton():data(0){};
singleton(const singleton&){};
singleton& operator = (const sigleton&);
static singleton* _instance;
int data;
}
singleton* singleton::_instance = new singleton();以上。
網(wǎng)頁名稱:設(shè)計模式之單例模式:singleton
當(dāng)前網(wǎng)址:http://www.chinadenli.net/article8/gegoip.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供全網(wǎng)營銷推廣、手機網(wǎng)站建設(shè)、網(wǎng)站策劃、品牌網(wǎng)站設(shè)計、服務(wù)器托管、網(wǎng)站改版
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)