iOS 单例模式
0.1 2017.09.07 13:36* 字数 427 阅读 755评论 0喜欢 11
一、介绍
iOS单例模式(Singleton)单例模式的意思就是只有一个实例。单例模式确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例。这个类称为单例类。
1、单例模式的要点:
一是某个类只能有一个实例;
二是它必须自行创建这个实例;
三是它必须自行向整个系统提供这个实例。
2、单例模式的优点:
1.实例控制:Singleton 会阻止其他对象实例化其自己的 Singleton 对象的副本,从而确保所有对象都访问唯一实例。
2.灵活性:因为类控制了实例化过程,所以类可以更加灵活修改实例化过程 IOS中的单例模式
二、实现单例
单例模式写法:
我们知道,创建对象的步骤分为申请内存(alloc)、初始化(init)这两个步骤,我们要确保对象的唯一性,因此在第一步这个阶段我们就要拦截它。
当我们调用alloc方法时,oc内部会调用allocWithZone这个方法来申请内存,我们覆写这个方法,然后在这个方法中调用shareInstance方法返回单例对象,这样就可以达到我们的目的。
拷贝对象也是同样的原理,覆写copyWithZone方法,然后在这个方法中调用shareInstance方法返回单例对象。
staticSLSingleton* _instance =nil;+(instancetype)shareInstance{staticdispatch_once_tonceToken;dispatch_once(&onceToken, ^{ _instance = [[superallocWithZone:NULL] init]; });return_instance;}+(id)allocWithZone:(struct_NSZone *)zone{return[SLSingleton shareInstance];}-(id) copyWithZone:(struct_NSZone *)zone{return[SLSingleton shareInstance];}
参考链接:
网友评论