IOS單例模式(Singleton)單例模式的意思就是只有一個(gè)實(shí)例。單例模式確保某一個(gè)類(lèi)只有一個(gè)實(shí)例,而且自行實(shí)例化并向整個(gè)系統(tǒng)提供這個(gè)實(shí)例。這個(gè)類(lèi)稱為單例類(lèi)。
1.單例模式的要點(diǎn): 顯然單例模式的要點(diǎn)有三個(gè);一是某個(gè)類(lèi)只能有一個(gè)實(shí)例;二是它必須自行創(chuàng)建這個(gè)實(shí)例;三是它必須自行向整個(gè)系統(tǒng)提供這個(gè)實(shí)例。
2.單例模式的優(yōu)點(diǎn): 一是實(shí)例控制:Singleton 會(huì)阻止其他對(duì)象實(shí)例化其自己的 Singleton 對(duì)象的副本,從而確保所有對(duì)象都訪問(wèn)唯一實(shí)例。 二是靈活性:因?yàn)轭?lèi)控制了實(shí)例化過(guò)程,所以類(lèi)可以更加靈活修改實(shí)例化過(guò)程 IOS中的單例模式
在objective-c中要實(shí)現(xiàn)一個(gè)單例類(lèi),至少需要做以下四個(gè)步驟:
1、為單例對(duì)象實(shí)現(xiàn)一個(gè)靜態(tài)實(shí)例,并初始化,然后設(shè)置成nil,
2、實(shí)現(xiàn)一個(gè)實(shí)例構(gòu)造方法檢查上面聲明的靜態(tài)實(shí)例是否為nil,如果是則新建并返回一個(gè)本類(lèi)的實(shí)例,
3、重寫(xiě)allocWithZone方法,用來(lái)保證其他人直接使用alloc和init試圖獲得一個(gè)新實(shí)力的時(shí)候不產(chǎn)生一個(gè)新實(shí)例,
4、適當(dāng)實(shí)現(xiàn)allocWitheZone,copyWithZone,release和autorelease。
下面以SurveyRunTimeData為例子:
?static SurveyRunTimeData *sharedObj = nil; //第一步:靜態(tài)實(shí)例,并初始化。@implementation SurveyRunTimeData+ (SurveyRunTimeData*) sharedInstance? //第二步:實(shí)例構(gòu)造檢查靜態(tài)實(shí)例是否為nil {? ??
@synchronized (self)? ? {? ? ? ??
if (sharedObj == nil)? ? ? ? {? ? ? ? ? ??
[[self alloc] init];? ? ? ??
}? ? }? ??
return sharedObj;
}
+ (id) allocWithZone:(NSZone *)zone //第三步:重寫(xiě)allocWithZone方法
{? ??
@synchronized (self) {? ? ? ?
?if (sharedObj == nil) {? ? ? ? ? ??
sharedObj = [super allocWithZone:zone];? ? ? ? ? ??
return sharedObj;? ? ? ??
}? ? }? ??
return nil;
}
- (id) copyWithZone:(NSZone *)zone //第四步{? ?
?return self;
}
- (id) retain{? ??
return self;
}
- (unsigned) retainCount{? ??
return UINT_MAX;
}
- (oneway void) release{?
?? }
- (id) autorelease{? ??
return self;
}- (id)init{? ??
@synchronized(self) {? ? ? ?
?[super init];//往往放一些要初始化的變量.? ? ? ??
return self;? ?
?}}
@end