面试官经常问单利模式,自打12年做java的时候就问,14年转行做iOS继续问。笔试题也是经常写。今天写下来也是为了来日面试直接拿来超超超超超超。。。。。
一、普通工具类单利
@interface Tools : NSObject
//SingleH(Tools)
+(instancetype)shareTools;
@end
@implementation Tools
//SingleM(Tools)
static Tools *_instance;
+(instancetype)allocWithZone:(struct _NSZone *)zone
{
//使用GCD一次函数
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [super allocWithZone:zone];
});
//添加同步锁
// @synchronized (self) {
// if (_instance == nil) {
// _instance = [super allocWithZone:zone];
// }
// }
return _instance;
}
+(instancetype)shareTools
{
return [[self alloc]init];
}
- (id)copy
{
return _instance;
}
-(id)mutableCopy
{
return _instance;
}
@end
二、宏定义单利工具
ifndef Single_h
define Single_h
define SingleH(name) +(instancetype)share##name;
define SingleM(name) static id _instance;\
+(instancetype)allocWithZone:(struct _NSZone *)zone
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [super allocWithZone:zone];
});
return _instance;
}
+(instancetype)share##name
{
return [[self alloc]init];
}
-(id)copy{
return _instance;
}
-(id)mutableCopy
{
return _instance;
}