码迷,mamicode.com
首页 > 其他好文 > 详细

单例模式-基本实现01

时间:2016-04-08 00:38:32      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:

 1 - (void)viewDidLoad
 2 {
 3     [super viewDidLoad];
 4     
 5     [self test];  
 6 }
 7 
 8 - (void)test
 9 {
10         XZMusicTool *tool = [[XZMusicTool alloc] init];
11         XZMusicTool *tool2 = [[XZMusicTool alloc] init];
12         XZMusicTool *tool3 = [XZMusicTool sharedMusicTool];
13         XZMusicTool *tool4 = [XZMusicTool sharedMusicTool];
14     
15         // copy 有可能会产生新的对象
16         // copy方法内部会调用- copyWithZone:
17         XZMusicTool *tool5 = [tool4 copy];
18     
19         NSLog(@"%@ %@ %@ %@ %@", tool, tool2, tool3, tool4, tool5);
20 }        

[[XZMusicTool alloc] init];

[XZMusicTool sharedMusicTool];

[tool4 copy];

以上三种方式都能保证创建出来的对象是同一个.

 

 1 .
 2 //  懒汉式
 3 
 4 #import "XZMusicTool.h"
 5 
 6 @implementation XZMusicTool
 7 static id _instance;
 8 
 9 /**
10  *  alloc方法内部会调用这个方法
11  */
12 + (id)allocWithZone:(struct _NSZone *)zone
13 {
14     if (_instance == nil) { // 防止频繁加锁
15         @synchronized(self) {
16             if (_instance == nil) { // 防止创建多次
17                 _instance = [super allocWithZone:zone];
18             }
19         }
20     }
21     return _instance;
22 }
23 
24 + (instancetype)sharedMusicTool
25 {
26     if (_instance == nil) { // 防止频繁加锁
27         @synchronized(self) {
28             if (_instance == nil) { // 防止创建多次
29                 _instance = [[self alloc] init];
30             }
31         }
32     }
33     return _instance;
34 }
35 
36 - (id)copyWithZone:(NSZone *)zone
37 {
38     return _instance;  // 既然可以copy,说明是已经创建了对象。
39 }
40 @end

 

列出下面代码做个比较:

 1 @implementation PayManager
 2 
 3 +(instancetype)sharedManager {
4 static dispatch_once_t onceToken; 5 static PayManager *_instance;
6 dispatch_once(&onceToken, ^{ 7 _instance = [[PayManager alloc] init]; 8 }); 9 return _instance; 10 } 11 12 @end

 

单例模式-基本实现01

标签:

原文地址:http://www.cnblogs.com/nxz-diy/p/5366163.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!