原文網(wǎng)址:[http://www.cnblogs.com/lyanet/archive/2013/01/11/2856468.html]
單例模式:
此單例模式的類只有一個(gè)實(shí)例,能夠自行實(shí)例化并向系統(tǒng)提供這個(gè)實(shí)例。該類稱為單例類。
1.特點(diǎn):
1.該類只能有一個(gè)實(shí)例
2.必須自行創(chuàng)建此實(shí)例
3.自行向系統(tǒng)提供該實(shí)例
2.優(yōu)點(diǎn):
1.訪問(wèn)的實(shí)例相同且唯一:因?yàn)閱卫J讲辉试S其他對(duì)象在進(jìn)行這個(gè)單例類的實(shí)例化。
2.靈活性:因?yàn)轭惪刂屏藢?shí)例化過(guò)程,所以類可以更加靈活修改實(shí)例化過(guò)程。
3.創(chuàng)建單例模式的三個(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è)本類的實(shí)例,
3、重寫allocWithZone方法,用來(lái)保證其他人直接使用alloc和init試圖獲得一個(gè)新實(shí)力的時(shí)候不產(chǎn)生一個(gè)新實(shí)例,
舉例(使用單例模式實(shí)現(xiàn)A、B兩個(gè)頁(yè)面之間的傳值):
思路:
A頁(yè)面:
//1. 定義一個(gè)靜態(tài)全局變量
static RootViewController *instance = nil;
//2. 實(shí)現(xiàn)類方法---實(shí)例構(gòu)造檢查靜態(tài)實(shí)例是否為nil
+ (instancetype) sharedInstance {
@synchronized(self) {
if (instance == nil) {
//如果為空,初始化單例模式
instance = [[RootViewController alloc] init];
}
}
return instance;
}
//3.重寫allocWithZone方法
//說(shuō)明:這里的的復(fù)寫目的是防止用戶無(wú)意之間采用[[RootViewController alloc] init]進(jìn)行初始化
+ (instancetype) allocWithZone:(struct _NSZone *)zone {
@synchronized(self) {
if (instance == nil) {
//說(shuō)明:這里的實(shí)例是進(jìn)行內(nèi)存的分配
instance = [super allocWithZone: zone];
}
}
return instance;
}
B頁(yè)面
//button的響應(yīng)事件里實(shí)現(xiàn)值得傳遞
- (void) backAction: (UIButton *) button {
//1) 取值
UITextField *textField = (UITextField *)[
self.view viewWithTag:2000];
//2) 通過(guò)單例模式修改值
RootViewController *rootViewController = [RootViewController sharedInstance];
rootViewController.label.text = textField.text;
//3) 關(guān)閉模態(tài)視圖
[self dismissViewControllerAnimated:YES completion:nil];
}