一、单例模式的基本信息
1.单例模式的作用:程序在运行过程中,可以保证一个类只有一个实例,而且这个实例容易于方便工程外部的访问,进而方便地控制了实例的个数,并且节约了系统资源。
2.单例模式的使用场景:在整个应用程序之中,共享一份资源,这份资源只用初始化一次即可。单例模式在MRC和ARC两种环境下的写法是有区别的,这里只对ARC环境下的写法做介绍,MRC的不再这里介绍。
二、单例模式的具体实现步骤
大概步骤分为四步:(1)在类的内部保留一个static修饰的全局变量(2)提供一个类方法,方便外界访问(3)重写allocWithZone:方法,创建唯一的实例(4)重写copyWithZone方法。
1.在ARC中单例模式的实现,需要在.m文件中保留一个全局的static的实例变量,eg:static id _instance;
2.重写allocWithZone:方法,创建唯一的实例,这里要注意线程安全问题
+ (id)allocWithZone:(struct _NSZone *)zone {
if (_instance == nil) { 防止频繁加锁
@synchronized(self) {
if(_instance == nil) { 防止创建多次
_instance = [super allocWithZone:zone];
}
}
}
return _instance;
}
3.提供一个类方法让工程外部文件访问唯一的实例
+ (instancetype)sharedTool {
if (_instance == nil) { 防止频繁加锁
@synchronized(self) {
if(_instance == nil) { 防止创建多次
_instance = [[self alloc] init];
}
}
}
return _instance;
}
4.实现copyWithZone:方法
- (id)copyWithZone:(struct _NSZone *)zone {
return _instance;
}
以上就是本章全部内容,欢迎关注三掌柜的微信公众号“iOS开发by三掌柜”,三掌柜的新浪微博“三掌柜666”,欢迎关注!