单例模式
一.为什么要用单例模式?
a.由于编程习惯的影响,在OC的MRC中,容易忽略释放开辟的内容。即alloc后,没有release。
b.在OC的ARC(xcode4.2以后新增的自动引用计数)中,重复创建多个同样内容的对象,导致OOM(out of memory)。
综上所述,引入了单例模式。
二.单例模式如何使用?
I.单例模式的特点:
a.有且只有一个全局唯一的实例
b.必须自行创建一个实例
c.必须提供一个全局实例,暴露可访问的方式
II.单例模式角色划分:
a.单例class
b.使用者(即客户端)
III.单例模式的实现:
约束:
a.提供一个静态实例,一般设置为nil(swfit、java同理)
b.提供一个函数用于创建单例,如果单例不存在就创建,存在的话就返回
c.OC中需要重写superClass的allocWithZone方法,保证初始化是一个单例(OC中重写的还有CopyWithZone相关方法、Swift中要将构造方法私有化、Java要构造方法私有化)
实现:
a.OC(非线程安全和线程安全):
1.非线程安全(标准单例)
static *ZLSingleton *instance = nil;//约束a
+(instancetype)sharedInstance {
//约束b
if(instance == nil) {
instance = [[ZLSingleton alloc] init];
}
return instance;
}
+(id)CopyWithZone:(struct _NSZone *)zone {
//约束c
if(instance == nil) {
instance = [super CopyWithZone:zone];
}
return instance;
}
2.线程安全(GCD、加锁等手段)
+ (instancetype *)sharedInstance {
static ZLSingleton *instance =nil;
staticdispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [[ZLSingletonalloc]init];
});
returninstance;
}为了防止外部使用alloc方法创建,同样要进行CopyWithZone的重写
+(id)CopyWithZone:(struct _NSZone *)zone {
if (instance == nil) {
staticdispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [super CopyWithZone:zone];
});
}
return instance;
}
以上案例均为懒汉式,即需要才创建。饿汉式的话,可以在+load里创建实例。
b.Swfit:
//线程不安全
final class ZLSingleton : NSObject {
//final关键字 让类不能被继承
private static var instance:ZLSingleton? = nil
class fun sharedInstance() -> ZLSingleton {
if (instance == nil) {
instance = ZLSingleton();
}
return instance!;
}
private override init() {
}
}
//线程安全
final class ZLSingleton : NSObject {
//final关键字 让类不能被继承
private static let instance:ZLSingleton? = ZLSingleton()
class fun sharedInstance() -> ZLSingleton {
return instance!;
}
private override init() {
}
}
除了以上案例,还可以用结构体来定义c.Java:
和swift差不多
Java还可以用枚举来实现