object-c 单例模式(包括ARC)

来源:互联网 发布:mysql 修复数据库 编辑:程序博客网 时间:2024/05/02 02:47

大家知道,单例模式是ios里面经常使用的模式,例如

[UIApplication sharedApplication] (获取当前应用程序对象)、 [UIDevicecurrentDevice](获取当前设备对象);

单例模式的写法也很多。

第一种:

[java] view plaincopy
  1. static Singleton *singleton = nil;  
  2.   
  3. // 非线程安全,也是最简单的实现  
  4. + (Singleton *)sharedInstance  
  5. {  
  6.     if (!singleton) {  
  7.         // 这里调用alloc方法会进入下面的allocWithZone方法  
  8.         singleton = [[self alloc] init];  
  9.     }  
  10.   
  11.     return singleton;  
  12. }  
  13.   
  14.   
  15. // 这里重写allocWithZone主要防止[[Singleton alloc] init]这种方式调用多次会返回多个对象  
  16. + (id)allocWithZone:(NSZone *)zone  
  17. {  
  18.     if (!singleton) {  
  19.         NSLog(@"进入allocWithZone方法了...");  
  20.         singleton = [super allocWithZone:zone];  
  21.         return singleton;  
  22.     }  
  23.   
  24.     return nil;  
  25. }  



第二种:

[java] view plaincopy
  1. // 加入线程安全,防止多线程情况下创建多个实例  
  2. + (Singleton *)sharedInstance  
  3. {  
  4.     @synchronized(self)  
  5.     {  
  6.         if (!singleton) {  
  7.             // 这里调用alloc方法会进入下面的allocWithZone方法  
  8.             singleton = [[self alloc] init];  
  9.         }  
  10.     }  
  11.   
  12.     return singleton;  
  13. }  
  14.   
  15.   
  16. // 这里重写allocWithZone主要防止[[Singleton alloc] init]这种方式调用多次会返回多个对象  
  17. + (id)allocWithZone:(NSZone *)zone  
  18. {  
  19.     // 加入线程安全,防止多个线程创建多个实例  
  20.     @synchronized(self)  
  21.     {  
  22.         if (!singleton) {  
  23.             NSLog(@"进入allocWithZone方法了...");  
  24.             singleton = [super allocWithZone:zone];  
  25.             return singleton;  
  26.         }  
  27.     }  
  28.       
  29.     return nil;  
  30. }  


第三种:

[java] view plaincopy
  1. __strong static Singleton *singleton = nil;  
  2. static int count = 0;  
  3.   
  4. // 这里使用的是ARC下的单例模式  
  5. + (Singleton *)sharedInstance  
  6. {  
  7.     // dispatch_once不仅意味着代码仅会被运行一次,而且还是线程安全的  
  8.     static dispatch_once_t pred = 0;  
  9.     dispatch_once(&pred, ^{  
  10.         singleton = [[self alloc] init];  
  11.     });  
  12.     return singleton;  
  13. }  
  14.   
  15. // 这里  
  16. + (id)allocWithZone:(NSZone *)zone  
  17. {  
  18.       
  19.     /* 这段代码无法使用, 那么我们如何解决alloc方式呢? 
  20.      dispatch_once(&pred, ^{ 
  21.         singleton = [super allocWithZone:zone]; 
  22.         return singleton; 
  23.     }); 
  24.      */  
  25.     @synchronized(self)  
  26.     {  
  27.         // 我们暂时用计数器来解决这个问题(暂时没有想到更好的办法)  
  28.         if (!singleton && !count)  
  29.         {  
  30.             count++;  
  31.             singleton = [super allocWithZone:zone];  
  32.             return singleton;  
  33.         }  
  34.     }  
  35.       
  36.     return nil;  
  37. }  

第三种是ARC下单例模式,也是比较方便的, 但是[[Singleton allocinit];这种情况下就可以生成多个对象了,怎么办呢,我们暂时先使用计数的方式来防止多次创建实例,如果大家有更好的方法,可以留言给我。谢谢~


原创粉丝点击