ARC
懒汉模式
#import "Singleton.h"
@implementation Singleton
static id _instance;
/**
* alloc方法内部会调用这个方法
*/
+ (instancetype)allocWithZone:(struct _NSZone *)zone{
if (_instance == nil) { // 防止频繁加锁
@synchronized(self) {
if (_instance == nil) { // 防止创建多次
_instance = [super allocWithZone:zone];
}
}
}
return _instance;
}
+ (instancetype)sharedSingleton{
if (_instance == nil) { // 防止频繁加锁
@synchronized(self) {
if (_instance == nil) { // 防止创建多次
_instance = [[self alloc] init];
}
}
}
return _instance;
}
- (id)copyWithZone:(NSZone *)zone{
return _instance;
}
@end
饿汉模式(不常用)
#import "HMSingleton.h"
@implementation Singleton
static id _instance;
/**
* 当类加载到OC运行时环境中(内存),就会调用一次(一个类只会加载1次)
*/
+ (void)load{
_instance = [[self alloc] init];
}
+ (instancetype)allocWithZone:(struct _NSZone *)zone{
if (_instance == nil) { // 防止创建多次
_instance = [super allocWithZone:zone];
}
return _instance;
}
+ (instancetype)sharedSingleton{
return _instance;
}
- (id)copyWithZone:(NSZone *)zone{
return _instance;
}
@end
GCD实现单例模式
@implementation Singleton
static id _instance;
+ (instancetype)allocWithZone:(struct _NSZone *)zone{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [super allocWithZone:zone];
});
return _instance;
}
+ (instancetype)sharedSingleton{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [[self alloc] init];
});
return _instance;
}
- (id)copyWithZone:(NSZone *)zone{
return _instance;
}
@end