单例模式

来源:互联网 发布:淘宝与03年的非典 编辑:程序博客网 时间:2024/04/29 07:55

1.单例设计模式(Singleton)
* 它可以保证某个类创建出来的对象永远只有1个

2.应用场景和优点

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

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


3> 实现

* MRC(非ARC)

* ARC

SoundTool.h

#import <Foundation/Foundation.h>@interface SoundTool : NSObject <NSCopying>+ (instancetype)shareSoundTool;@end


SoundTool.m

#import "SoundTool.h"@implementation SoundToolstatic 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;}

可修改为宏包装使用。
                                             
0 0