单例设计模式-01-GCD-单例

 1 //
 2 //  LYMusicTool.m
 3 //  01-单例设计模式
 4 //
 5 //  Created by mac on 16/4/22.
 6 //  Copyright © 2016年 mac. All rights reserved.
 7 
 8 //alloc的本质是调用:-->>allocWithZone:方法
 9 
10 #import "LYMusicTool.h"
11 
12 @interface LYMusicTool ()
13 
14 @end
15 
16 @implementation LYMusicTool
17 /**
18  *  1. 创建一个全局变量
19  */
20 id _music;
21 
22 - (NSArray *)musics {
23     
24     if (!_musics) {
25         
26         _musics = [NSMutableArray array];
27         
28         //加载歌曲
29     }
30     
31     return _musics;
32 }
33 
34 /**
35  *  2. 重写allocWithZone:只分配一次内存
36  */
37 + (instancetype)allocWithZone:(struct _NSZone *)zone {
38     
39     @synchronized(self) { //加互斥锁防止多线程同时进来访问,更加安全,真正的单例
40         
41         if (!_music) {
42             
43             _music = [super allocWithZone:zone];
44         }
45     }
46     
47     return _music;
48 }
49 
50 /**
51  *  3. 既保证了单例(只分配一次内存),又保证了只init一次;
52  */
53 + (instancetype)sharedMusicTool {
54     
55     @synchronized(self) {
56         
57         if (!_music) {
58             
59             _music = [[self alloc] init];
60         }
61     }
62     return _music;
63 }
64 
65 /*
66  *   4. 此方法能保证单例(只分配一次内存),但是初始化多次
67  
68  + (instancetype)sharedMusicTool {
69  
70  return [[self alloc] init];
71  }
72  */
73 
74 /**
75  *  5.copy使用
76  *
77  *  1). 遵守coping协议
78  *  2). 重写协议方法copyWithZone:拦截copy产生新对象
79  *  3). 不用判断_music是否空,是因为copy的前提是有对象,有对象 所以_music有值
80  */
81 - (id)copyWithZone:(NSZone *)zone {
82     
83     return _music;
84 }
85 @end

 

posted on 2016-04-22 10:50  爱你久久iOS  阅读(155)  评论(0编辑  收藏  举报

导航