首页 > 系统 > iOS > 正文

单例模式及其在iOS中的应用

2019-11-07 22:59:54
字体:
来源:转载
供稿:网友

单例模式(Singleton Pattern) 确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例,这个类成为单例类,它提供全局访问方法。

单例模式三要点:

某个类只能有一个实例它必须自行创建这个实例它必须自行向整个系统提供这个实例

使用场景:当一个系统要求只有一个实例时可使用单例模式。

iOS 单例的两种写法: 第一种:

//1.设置成静态全局变量static Setting *set = nil;+(Setting *)sharedSetting{ @synchronized(self){//2.保证线程安全 // 3.当对象不存在时,创建对象,第二次再调用方法的时候,由于set是静态的,所以不为空,不会再重新创建对象 if (!set) { set = [[Setting alloc]init]; } } //返回自己 return set;}//这个方法是在调用alloc方法时,alloc内部实际调用的创建对象的方法//我们重写这个方法,保证在这个方法的内部创建的对象就是set对象即可+(id)allocWithZone:(struct _NSZone *)zone{ @synchronized(self){ if (!set) { set = [super allocWithZone:zone]; } } return set;}

第二种:

+ (id)sharedSetting{ static Setting *setting = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ setting = [[self alloc] init]; }); return setting;}+(id)allocWithZone:(struct _NSZone *)zone{ static Setting *setting = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ setting = [super allocWithZone:zone]; }); return setting;}

以上两种方法对于只用【shareSetting】类方法获取的话【allocWithZone】方法创建实例是可以不重写的,但是,为防止一不小心用alloc方法创建实例,座椅最好还是重写一下。而且在实际中,为保证对象的绝对唯一,并不是只需重写这一个方法,还有 copyWithZone 等

//注意:在实际中,若想保证对象的绝对唯一,并不是只需重写这一个方法,还有 copyWithZone 等//实现这个方法的类- (id)copyWithZone:(nullable NSZone *)zone{ return self;}- (id)mutableCopyWithZone:(nullable NSZone *)zone{ return self;}

结果展示一下: 这里写图片描述

其中要想对copyWithZone方法进行进一步了解的点这里

如有不当,欢迎指正。


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表