单例
##1.单例模式:
单一 实例(对象),
也就是说,希望类的对象无论如何创建,永远都是那一个对象。
##2.如何实现?
a.无论是哪一个创建对象的方式,都要先alloc。
b.alloc方法的内部,调用了allocWithZone:方法
并且不建议重写alloc方法,如果真的要重写alloc方法,可以重写allocWithZone:方法,allocWithZone:方法是用来创建对象的并且被alloc调用。
c.GCD方法实现代码(宏定义):
“`objc
//.h文件
define LSQSingleton_h(name) + (instancetype)shared##name;
//.m文件
define LSQSingleton_m(name)\
static id _instance;\
static dispatch_once_t oneToken;\
\
+ (instancetype)allocWithZone:(struct _NSZone *)zone\
{\
dispatch_once(&oneToken, ^{\
_instance = [super allocWithZone:zone];\
});\
return _instance;\
}\
\
+ (instancetype)shared##name\
{\
dispatch_once(&oneToken, ^{\
_instance = [[self alloc] init];\
});\
return _instance;\
}\
- (id)copyWithZone:(NSZone *)zone\
{\
return _instance;\
}
d.利用互斥锁实现单例:
```objc
static id _instance;
+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
@synchronized(self) {
if (_instance == nil) {
_instance = [super allocWithZone:zone];
}
}
return _instance;
}
+ (instancetype)sharedInstance
{
@synchronized(self) {
if (_instance == nil) {
_instance = [[self alloc] init];
}
}
return _instance;
}
- (id)copyWithZone:(NSZone *)zone
{
return _instance;
}
##3.什么时候要使用单例模式?
单例模式的特点:无论对象如何创建,创建多少次,在哪里创建,
返回的都是同一个对象
所以,单例对象可以用来共享一些数据。
有一些数据在很多地方都要用到。
那么,我们就可以把数据存储到单例对象中。
这样,在任何时候,我们通过该单例对象都可以取得之前存储的数据。
##4.规范
a.如果是一个单例类,要求该单例类提供一个方法来得到单例对象。
这个类方法可以取名为“shared类名”或者“default类名”
规范,应该提供一个类方法:defaultXX或者sharedXXX方法来返回单例对象