iOS單例模式(一)

什么是單例 ?

單例模式是一種常用的軟件設(shè)計模式。在它的核心結(jié)構(gòu)中只包含一個被稱為單例類的特殊類。通過單例模式可以保證系統(tǒng)中一個類只有一個實例而且該實例易于外界訪問,從而方便對實例個數(shù)的控制并節(jié)約系統(tǒng)資源。如果希望在系統(tǒng)中某個類的對象只能存在一個,單例模式是最好的解決方案。

iOS開發(fā)中如何使用單例?

傳統(tǒng)的單例構(gòu)造方法

+ (id)sharedInstance {

static id sharedInstance;

if(sharedInstance == nil){

sharedInstance = [[]self alloc] init]

}

return sharedInstance;

}

多線程下的隱患 在多線程的情況下,如果兩個線程幾乎同時調(diào)用sharedInstance()方法會發(fā)生什么呢?

有可能會創(chuàng)建出兩個該類的實例。

為了防止這種情況 我們通常會加上鎖

+ (id)sharedInstance {

static id sharedInstance;

@synchronized(self)

if(sharedInstance == nil)

{ sharedInstance = [[]self alloc] init]

} }

return sharedInstance;

}

dispatch_once iOS 4.0 引進了 GCD ,其中的 **dispatchonce**,它即使是在多線程環(huán)境中也能安全地工作,非常安全。dispatchonce是用來確保指定的任務(wù)將在應(yīng)用的生命周期期間,僅執(zhí)行一次。以下是一個典型的源代碼以初始化的東西。它可以優(yōu)雅通過使用dispatch_once來創(chuàng)建一個單例。

+ (id)sharedInstance {

static dispatch_once_t once;

static id sharedInstance;

dispatch_once(&once, ^{

sharedInstance = [[self alloc] init]; });

return sharedInstance;

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容