①定義
單例模式確保某一個(gè)類只有一個(gè)實(shí)例陵叽,而且自行實(shí)例化并向整個(gè)系統(tǒng)提供這個(gè)實(shí)例。
②優(yōu)缺點(diǎn)
優(yōu)點(diǎn):為頻繁訪問(wèn)的第三方工具提供了唯一的實(shí)例寥假,從而節(jié)約系統(tǒng)資源妄壶,不用再頻繁地創(chuàng)建和銷毀對(duì)象,無(wú)疑提高了系統(tǒng)的性能键耕。
缺點(diǎn):不可過(guò)多的創(chuàng)建單例寺滚,因?yàn)閱卫龔膭?chuàng)建后到徹底關(guān)閉程序前都會(huì)一直存在,如果過(guò)多的創(chuàng)建單例無(wú)疑浪費(fèi)系統(tǒng)資源和影響系統(tǒng)效率屈雄。
③代碼實(shí)現(xiàn)
創(chuàng)建一個(gè)對(duì)象是先調(diào)用alloc方法分配對(duì)象內(nèi)存村视,再調(diào)用init方法進(jìn)行初始化,那么實(shí)現(xiàn)單例酒奶,重寫allocWithZone:方法就可以了蚁孔,用GCD的dispatch_once函數(shù)是比較簡(jiǎn)單的一種方式,因?yàn)橛幸粋€(gè)dispatch_once_t類型參數(shù)能保證只執(zhí)行一次。
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
static dispatch_once_t onceToken;
static id instance;
dispatch_once(&onceToken, ^{
instance = [super allocWithZone:zone];
});
return instance;
}
④宏定義單例模式
如果多個(gè)類要實(shí)現(xiàn)單例模式惋嚎,我們可以定義個(gè)一個(gè)頭文件SingletonPattern.h杠氢,里面定義兩個(gè)宏,分別是聲明與實(shí)現(xiàn)另伍。
#ifndef SingletonPattern_h
#define SingletonPattern_h
#define WD_SINGLETON_PATTERN_INTERFACE(name) +(instancetype)shared##name;
#define WD_SINGLETON_PATTERN_IMPLEMENTATION(name) +(instancetype)shared##name {\
return [[self alloc] init];\
}\
+ (instancetype)allocWithZone:(struct _NSZone *)zone {\
static dispatch_once_t onceToken;\
static id instance;\
dispatch_once(&onceToken, ^{\
instance = [super allocWithZone:zone];\
});\
return instance;\
}\
//- (id)copyWithZone:(NSZone *)zone {\
//return self;\
//}
#endif
實(shí)現(xiàn)單例修然,只要導(dǎo)入頭文件"SingletonPattern.h"
,
在.h文件寫WD_SINGLETON_PATTERN_INTERFACE(類名)
,
在.m文件寫WD_SINGLETON_PATTERN_IMPLEMENTATION(類名)
,就可以了。