单例设计模式

2017-12-30  本文已影响21人  IreneWu

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

2> 作用(为什么要用)

3> 怎么实现

//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; 
}

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; 
}
上一篇 下一篇

猜你喜欢

热点阅读