码迷,mamicode.com
首页 > 其他好文 > 详细

重温-单例模式

时间:2015-09-14 11:56:18      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:

1. 单例设计模式(Singleton)

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

2. 作用

* 节省内存开销。

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

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

3. 实现

* MRC

* ARC

SoundTool.h

技术分享
1 #import <Foundation/Foundation.h>
2 
3 @interface SoundTool : NSObject <NSCopying>
4 
5 + (instancetype)shareSoundTool;
6 
7 @end
View Code

SoundTool.m

技术分享
#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. 建议包装成宏使用

重温-单例模式

标签:

原文地址:http://www.cnblogs.com/ccoding2015/p/4806537.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!