iOS-单例模式(懒汉式和饿汉式)和GCD实现

//
//  HMMusicTool.h
//  03-单例模式-Singleton(掌握)
//
//  Created by apple on 14-9-16.
//  Copyright (c) 2014年 heima. All rights reserved.
//  播放音乐

#import <Foundation/Foundation.h>

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



//
//  HMMusicTool.m
//  03-单例模式-Singleton(掌握)
//
//  Created by apple on 14-9-16.
//  Copyright (c) 2014年 heima. All rights reserved.
//  懒汉式

#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
//
//  HMDataTool.h
//  03-单例模式-Singleton(掌握)
//
//  Created by apple on 14-9-16.
//  Copyright (c) 2014年 heima. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface HMDataTool : NSObject
+ (instancetype)sharedDataTool;
@end


//
//  HMDataTool.m
//  03-单例模式-Singleton(掌握)
//
//  Created by apple on 14-9-16.
//  Copyright (c) 2014年 heima. All rights reserved.
//

#import "HMDataTool.h"

@implementation HMDataTool
// 用来保存唯一的单例对象
static id _instace;

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

+ (instancetype)sharedDataTool
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instace = [[self alloc] init];
    });
    return _instace;
}

- (id)copyWithZone:(NSZone *)zone
{
    return _instace;
}

@end

 

posted @ 2015-10-03 14:30  微博和csdn还有你  阅读(438)  评论(0编辑  收藏  举报