單例模版
OC
@interface XQSingleton : NSObject
+ (instancetype)shareInstance;
@end
@implementation XQSingleton
+ (instancetype)shareInstance{
static XQSingleton *shareInstance;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
shareInstance = [[super allocWithZone:NULL] init];
});
return shareInstance;
}
+ (instancetype)allocWithZone:(struct _NSZone *)zone{
return [self shareInstance];
}
- (id)copy{
return self;
}
- (id)mutableCopy{
return self;
}
以上代碼有以下幾點(diǎn)一一展開說(shuō):
在XQSingleton的@interface中聲明shareInstance接口瑟慈,提供給外部調(diào)用返回單例對(duì)象臀晃。
在類實(shí)現(xiàn)中shareInstance使用static XQSingleton *shareInstance盆色,這種靜態(tài)局部對(duì)象是為了保持返回對(duì)象的唯一性鹅士。
使用GCD的dispatch_once函數(shù)確保該對(duì)象的初始化方法只執(zhí)行一次扼鞋,保證了線程安全蟹演。
初始化使用[super allocWithZone:NULL]是為了重載當(dāng)前類的allocWithZone方法诵原,只能使用父類的對(duì)象分配方法來(lái)創(chuàng)建對(duì)象英妓。
重載allocWithZone方法是為了防止外部調(diào)用alloc創(chuàng)建出另外一個(gè)新的XQSingleton對(duì)象。
重載copy和mutableCopy方法時(shí)為了防止外部調(diào)用copy或者mutableCopy方法時(shí)绍赛,生成新的對(duì)象蔓纠。
Swift版本
final class Singleton {
private init() {}
static let shared = Singleton()
}
final保證類不能被繼承,避免可以子類化,進(jìn)而進(jìn)行改寫.
初始化方法private,保證無(wú)法被調(diào)用,這樣就保證了對(duì)象的唯一性.
可以看到,Swift的單例比OC的簡(jiǎn)潔安全不少