单例

单例ARC和MRC写法

1:什么是单例模式?

  • 类的对象成为系统中唯一的实例,提供一个访问点,供客户类 共享资源
  • 单例就是无论怎么创建都只能有一个实例对象

2:什么情况下使用单例?

  1. 类只能有一个实例,而且必须从一个为人熟知的访问点对其进行访问,比如工厂方法。
  2. 这个唯一的实例只能通过子类化进行扩展,而且扩展的对象不会破坏客户端代码。

3:创建单例对象的方法一般以什么开头?

  1. 一般情况下创建一个单例对象都有一个与之对应的类方法
  2. 一般情况下用于创建单例对象的方法名称都以share开头, 或者以default开头

4:单例在多线程的应用?

多线程中的单例

+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
    // 以下代码在多线程中也能保证只执行一次
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[super allocWithZone:zone] init];
    });
    return _instance;
}

 

22.单例宏抽取

1:如何将单例抽取成宏?如何在宏中判断当前是ARC还是MRC?

  • 单例宏定义
  • 以后就可以使用interfaceSingleton来替代后面的方法声明
#define interfaceSingleton(name)  +(instancetype)share##name

#if __has_feature(objc_arc)
// ARC
#define implementationSingleton(name)  
+ (instancetype)share##name 
{ 
name *instance = [[self alloc] init]; 
return instance; 
} 
static name *_instance = nil; 
+ (instancetype)allocWithZone:(struct _NSZone *)zone 
{ 
static dispatch_once_t onceToken; 
dispatch_once(&onceToken, ^{ 
_instance = [[super allocWithZone:zone] init]; 
}); 
return _instance; 
} 
- (id)copyWithZone:(NSZone *)zone{ 
return _instance; 
} 
- (id)mutableCopyWithZone:(NSZone *)zone 
{ 
,return _instance; 
}
#else
// MRC

#define implementationSingleton(name)  
+ (instancetype)share##name 
{ 
name *instance = [[self alloc] init]; 
return instance; 
} 
static name *_instance = nil; 
+ (instancetype)allocWithZone:(struct _NSZone *)zone 
{ 
static dispatch_once_t onceToken; 
dispatch_once(&onceToken, ^{ 
_instance = [[super allocWithZone:zone] init]; 
}); 
return _instance; 
} 
- (id)copyWithZone:(NSZone *)zone{ 
return _instance; 
} 
- (id)mutableCopyWithZone:(NSZone *)zone 
{ 
return _instance; 
} 
- (oneway void)release 
{ 
} 
- (instancetype)retain 
{ 
return _instance; 
} 
- (NSUInteger)retainCount 
{ 
return  MAXFLOAT; 
}
#endif
原文地址:https://www.cnblogs.com/dreamWanweidong/p/4998813.html