单例模式

单例模式

一.为什么要用单例模式?

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还可以用枚举来实现

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值