单例模式之懒汉模式

HMMusicTool.h

#import <Foundation/Foundation.h>

@interface HMMusicTool : NSObject
+ (instancetype)sharedMusicTool;
@end

HMMusicTool.m

#import "HMMusicTool.h"

@implementation HMMusicTool
static id _instance;

/**
 *  alloc方法内部会调用这个方法
 */
+ (id)allocWithZone:(struct _NSZone *)zone
{
    if (_instance == nil) { // 防止频繁加锁
        @synchronized(self) {
            if (_instance == nil) { // 防止创建多次
                _instance = [super allocWithZone:zone];
            }
        }
    }
    return _instance;
}

+ (instancetype)sharedMusicTool
{
    if (_instance == nil) { // 防止频繁加锁
        @synchronized(self) {
            if (_instance == nil) { // 防止创建多次
                _instance = [[self alloc] init];
            }
        }
    }
    return _instance;
}

- (id)copyWithZone:(NSZone *)zone
{
    return _instance;
}
@end

 

posted @ 2015-11-20 12:40  Z了个L  阅读(170)  评论(0编辑  收藏  举报