单例

单例

 ##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方法来返回单例对象

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值