一、简介
单例模式:一个类只有一个实例。单例模式(Singleton)的目的是为了保证在一个进程中,某个类有且仅有一个实例。
二、创建单例
1、@synchronized保证线程安全的懒加载
使用@synchronized保证线程安全的懒加载写法,但是由于@synchronized是互斥锁导致性能比较低
+ (Singleton *)sharedInstance {
@synchronized (self) {
if (_instance == nil) {
_instance = [[Singleton alloc]init];
}
}
return _instance;
}
2、GCD的dispatch_once
使用GCD中的dispatch_once写法,同时满足了线程安全和静态分析器的要求
static Singleton *_instance = nil;
+ (Singleton *)sharedInstance {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [[Singleton alloc]init];
});
return _instance;
}
看了一下苹果官方的示例代码示例代码SimpleNetworkStreams,也是推荐方法二,使用GCD中的dispatch_once写法创建单例
点击 Download Sample Code 即可下载查看
苹果给出示例代码SimpleNetworkStreams如下:
@synthesize networkOperationCount = _networkOperationCount;
+ (NetworkManager *)sharedInstance
{
static dispatch_once_t onceToken;
static NetworkManager * sSharedInstance;
dispatch_once(&onceToken, ^{
sSharedInstance = [[NetworkManager alloc] init];
});
return sSharedInstance;
}
以上两种单例模式的实现都不能保证Singleton是唯一的,因为通过[[Single alloc]init]方式创建仍然会创建出新的实例
3、allocWithZone和copyWithZone申请分配空间创建(创建绝对单例)
通过alloc / new / copy方法来创建绝对单例
alloc / new --> allocWithZone ;copy --> copyWithzone来分配空间
alloc / new / copy方法的内部就是调用了allocWithZone方法和copyWithzone方法,allocWithZone和copyWithzone方法的作用就是申请分配空间创建对象并将创建的对象返回
注意:如果需要copy,需要遵守NSCopying协议,以及在copyWithZone中,直接返回self
static Singleton *_instance = nil;
+ (instancetype )sharedInstance {
if (_instance == nil) {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [[Singleton alloc]init];
});
}
return _instance;
}
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
if (_instance == nil) {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [super allocWithZone:zone];
});
}
return _instance;
}
- (instancetype)copyWithZone:(NSZone *)zone {
return _instance;
}