您的位置:首页 > 其它

重温-单例模式

2015-09-14 10:44 162 查看
1. 单例设计模式(Singleton)

* 保证某个类创建出来的对象永远只有一个

2. 作用

* 节省内存开销。

* 如果有些数据,整个程序中都用得上,只需要使用同一份资源(保证大家访问的数据是相同一致的)

* 一般来说工具类设计为单例模式合适

3. 实现

* MRC

* ARC

SoundTool.h

#import "SoundTool.h"

@implementation SoundTool

static id _instance = nil;

+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
if (_instance == nil) {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [super allocWithZone:zone];
});
}
return _instance;
}

+ (instancetype)shareSoundTool
{
return [[self alloc] init];
}

- (instancetype)init
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [super init];
});
return _instance;
}

+ (instancetype)copyWithZone:(struct _NSZone *)zone
{
return _instance;
}

+ (instancetype)mutableCopyWithZone:(struct _NSZone *)zone
{
return _instance;
}

//以下三个为非ARC使用
- (oneway void)release
{
}

- (instancetype)retain
{
return _instance;
}

- (NSUInteger)retainCount
{
return 1;
}


View Code
4. 建议包装成宏使用
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: