单例设计模式

ARC下基础写法:

static AudioTool *instance;
+ (instancetype)sharedAudioTool{
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[AudioTool alloc] init];
    });
    return instance;
}

注意:由于viewController.m中alloc和shared调用的顺序不一样,所以后面的实现方法里面都重写一下dispatch_once,但是copy是对象copy,所以不用重写

+ (instancetype)allocWithZone:(struct _NSZone *)zone{
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [super allocWithZone:zone];
    });
    return instance;
}
- (id)copyWithZone:(NSZone *)zone{
    return instance;
}

MRC下除上面三个方法外,还要多写四个方法

-(oneway void)release{
    //不做事情
}

-(instancetype)retain{
     return instance;
}
-(NSUInteger)retainCount{
    return 1;
}
- (instancetype)autorelease{
    return instance;
}

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