单例设计模式

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

2> 作用(为什么要用)

  • 节省内存开销
  • 如果有一些数据, 整个程序中都用得上, 只需要使用同一份资源(保证大家访问的数据是相同的,一致的)
  • 一般来说, 工具类设计为单例模式比较合适

3> 怎么实现

  • MRC(非ARC)
//static保证全局变量不让别人访问
static MJSoundTool *_soundTool = nil;

/**
 *  alloc方法内部会调用allocWithZone:
 *  zone : 系统分配给app的内存
 */
+ (id)allocWithZone:(struct _NSZone *)zone
{
    if (_soundTool == nil) {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{ // 安全(这个代码只会被调用一次)
            _soundTool = [super allocWithZone:zone];
        });
    }
    return _soundTool;
}

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

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

- (oneway void)release
{

}

- (id)retain
{
    return self;
}

- (NSUInteger)retainCount
{
    return 1;
}

+ (id)copyWithZone:(struct _NSZone *)zone 
{ 
    return _instace; 
} 
 
+ (id)mutableCopyWithZone:(struct _NSZone *)zone 
{ 
    return _instace; 
}

  • ARC
static id _instance = nil;

+ (id)allocWithZone:(struct _NSZone *)zone
{
    if (_instance == nil) {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{ // 安全(这个代码只会被调用一次)
            _instance = [super allocWithZone:zone];
        });
    }
    return _instance;
}

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

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

+ (id)copyWithZone:(struct _NSZone *)zone 
{ 
    return _instace; 
} 
 
+ (id)mutableCopyWithZone:(struct _NSZone *)zone 
{ 
    return _instace; 
}

你可能感兴趣的:(单例设计模式)