1.最简单的单例写法
static Sigleton *sigletonA = nil;
+(instancetype)standardA{
if (!sigletonA) {
sigletonA = [[self alloc] init];
}
return sigletonA;
}
2.重写allocWithZone方法
static Sigleton *sigleton = nil;
+(instancetype)standard{
if (!sigleton) {
sigleton = [[self allocWithZone:NULL] init];
}
return sigleton;
}
+ (instancetype) allocWithZone:(struct _NSZone *)zone{
if(sigleton == nil){
sigleton = [super allocWithZone:zone];
}
return sigleton;
}
static Sigleton *sigleton1 = nil;
+(instancetype)standard_b{
@synchronized(self){
if(sigleton1 == nil){
sigleton1 = [[self alloc] init];
}
}
return sigleton1;
}
+(instancetype)standard_a{
static Sigleton *Sigleton0 = nil;
static dispatch_once_t predicate;
dispatch_once(&predicate, ^{
Sigleton0 = [[self alloc] init];
});
return Sigleton0;
}
测试代码:
Sigleton *sigleton1=[SigletonstandardA];
Sigleton *sigleton2=[SigletonstandardA];
Sigleton *sigleton3=[Sigletonstandard];
Sigleton *sigleton4=[Sigletonstandard];
Sigleton *sigleton5=[Sigletonstandard_a];
Sigleton *sigleton6=[Sigletonstandard_a];
Sigleton *sigleton7=[Sigletonstandard_b];
Sigleton *sigleton8=[Sigletonstandard_b];
//单例的写法多种多样,欢迎大家与我多多交流。