單例模式可以保證在程序運(yùn)行的過(guò)程中盛龄,一個(gè)類只存在一個(gè)對(duì)象航缀,而且該實(shí)例易于供外界訪問(wèn)夜牡。這個(gè)對(duì)象只有在該程序運(yùn)行結(jié)束后才會(huì)銷毀与纽。
因?yàn)橹淮嬖谝粋€(gè)對(duì)象,所以我們保證每次調(diào)用alloc生成的對(duì)象是同一塊地址即可塘装,但是使用alloc的時(shí)候急迂,alloc會(huì)調(diào)用其父類的allocwithzone方法分配內(nèi)存,所以我們要重寫allocwithzone方法
實(shí)現(xiàn)單例模式有兩種方法蹦肴。
方法1:GCD方式實(shí)現(xiàn)
1.allocwithzone方法的重寫
static Person *_person;
+(instancetype)allocWithZone:(struct _NSZone *)zone
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_person = [super allocWithZone:zone];
});
return _person;
}
2.實(shí)現(xiàn)單例的shared方法
+ (instancetype)sharedPerson
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_person = [[self alloc] init];
});
return _person;
}
3.重寫copy方法
@interface Person() <NSCopying>
@end
- (id)copyWithZone:(NSZone *)zone
{
return _person;
}
方法二:加鎖實(shí)現(xiàn)
1.allocwithzone方法的重寫
static Person *_person;
+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
@synchronized (self) {
if (_person == nil) {
_person = [super allocWithZone:zone];
}
}
return _person;
}
2.實(shí)現(xiàn)單例的shared方法
+ (instancetype)sharedPerson
{
@synchronized (self) {
if (_person == nil) {
_person = [[self alloc] init];
}
}
return _person;
}
3.重寫copy方法
@interface Person() <NSCopying>
@end
- (id)copyWithZone:(NSZone *)zone
{
return _person;
}