Objective-c单例模式详解

单例模式出现以后,关于它的争执就一直存在。在开发项目中,有很多时候我们需要一个全局的对象,而且要保证全局有且仅有一份即可。没错,单例在这个时候就是最佳的选择,但是需要注意的是:在多线程的环境下也需要做好线程保护。其实系统已经有很多单例存在,例如UIApplication、NSNotification、NSFileManager等等就是很不错的例子——我们总有时候需要用到单例模式,不过写起代码来还是需要考量考量。

  1. 我们先来看一个最简单的单例,假设我们有一个testClass的类需要实现单例:

     + (id)sharedInstance {  
         static testClass *sharedInstance = nil;  
         if (!sharedInstance) {  
             sharedInstance = [[self alloc] init];  
         }  
         return sharedInstance;  
     }  
    
  2. 熟悉单例的童鞋一眼就能看出,这里根本没有考虑线程安全的问题,需要加上线程锁。

     + (id)sharedInstance {  
         static testClass *sharedInstance = nil;  
         @synchronized(self) {  
             if (!sharedInstance) {  
                 sharedInstance = [[self alloc] init];  
             }  
         }  
         return sharedInstance;  
     }  
    
  3. 这是很常见的写法。不过,在GCD推出后,有个dispatch_once方法,可以使单例的实现更加容易,dispatch_once的函数原型如下:

     void dispatch_once(dispatch_once_t *predicate, dispatch_block_t block);  
    

    我们可以看到这个函数接收一个dispatch_once_t的参数,还有一个块参数。对于一个给定的predicate 来说,该函数会保证相关的块必定会执行,而且只执行一次,最重要的是——这个方法是完全线程安全的。需要 注意的是,对于只需要执行一次的块来说,传入的predicate必须是完全相同的,所以predicate常常会用 static或者global来修饰。

     + (id)sharedInstance {  
         static testClass *sharedInstance = nil;  
         static dispatch_once_t once;  
         dispatch_once(&once, ^{  
             sharedInstance = [[self alloc] init];  
         });  
         return sharedInstance;  
     }  
    
  4. 我们知道,创建对象的步骤分为申请内存(alloc)、初始化(init)这两个步骤,我们要确保对象的唯一性,因此在第一步这个阶段我们就要拦截它。当我们调用alloc方法时,OC内部会调用allocWithZone这个方法来申请内存,我们重写这个方法,然后在这个方法中调用shareInstance方法返回单例对象,这样就可以达到我们的目的。拷贝对象也是同样的原理,重写copyWithZone方法,然后在这个方法中调用shareInstance方法返回单例对象。

下面来看看两组例子:

一般写法:

#import <Foundation/Foundation.h>

@interface SingleClass : NSObject

+(instancetype) shareInstance ;

@end
 
 
#import "SingleClass.h"

@implementation SingleClass

static SingleClass *_sharedInstance = nil;

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

@end

具体使用,ViewController:

#import "ViewController.h"
#import "SingleClass.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    NSLog(@"开始《《《");
    SingleClass *obj1 = [SingleClass shareInstance] ;
    NSLog(@"obj1 = %@.", obj1) ;
    
    SingleClass *obj2 = [SingleClass shareInstance] ;
    NSLog(@"obj2 = %@.", obj2) ;
    
    SingleClass *obj3 = [[SingleClass alloc] init] ;
    NSLog(@"obj3 = %@.", obj3) ;
    
    NSLog(@"结束》》》");
}

@end

输出结果为 :

2016-04-11 15:49:29.494 aotulayoutDemo[7267:202275] 开始《《《
2016-04-11 15:49:29.495 aotulayoutDemo[7267:202275] obj1 = <SingleClass: 0x7f901142d660>.
2016-04-11 15:49:29.495 aotulayoutDemo[7267:202275] obj2 = <SingleClass: 0x7f901142d660>.
2016-04-11 15:49:29.495 aotulayoutDemo[7267:202275] obj3 = <SingleClass: 0x7f901160e3a0>.
2016-04-11 15:49:29.495 aotulayoutDemo[7267:202275] 结束》》》

在这里可以看到,当我们调用shareInstance方法时获取到的对象是相同的,但是当我们通过alloc和init来构造对象的时候,得到的对象却是不一样的。我们通过不同的途径得到不同的对象,显然是不行的。我们必须要确保对象的唯一性,所以我们就需要封锁用户通过alloc和init以及copy来构造对象这条道路。

下面来看看严谨的写法:

#import "Singleton.h"
 
@implementation Singleton
 
static Singleton* _instance = nil;
 
+(instancetype) shareInstance
{
    static dispatch_once_t onceToken ;
    dispatch_once(&onceToken, ^{
        _instance = [[super allocWithZone:NULL] init] ;
    }) ;
     
    return _instance ;
}
 
+(id) allocWithZone:(struct _NSZone *)zone
{
    return [Singleton shareInstance] ;
}
 
-(id) copyWithZone:(struct _NSZone *)zone
{
    return [Singleton shareInstance] ;
}
 
@end

再看看效果如何,ViewController:

#import "ViewController.h"
#import "SingleClass.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    NSLog(@"开始《《《");
    SingleClass *obj1 = [SingleClass shareInstance] ;
    NSLog(@"obj1 = %@.", obj1) ;
    
    SingleClass *obj2 = [SingleClass shareInstance] ;
    NSLog(@"obj2 = %@.", obj2) ;
    
    SingleClass *obj3 = [[SingleClass alloc] init] ;
    NSLog(@"obj3 = %@.", obj3) ;
    
    SingleClass* obj4 = [[SingleClass alloc] init] ;
    NSLog(@"obj4 = %@.", [obj4 copy]) ;

    NSLog(@"结束》》》");
}

@end

输出结果:

2016-04-11 15:56:27.261 aotulayoutDemo[7373:205889] 开始《《《
2016-04-11 15:56:27.263 aotulayoutDemo[7373:205889] obj1 = <SingleClass: 0x7fd9e261d690>.
2016-04-11 15:56:27.263 aotulayoutDemo[7373:205889] obj2 = <SingleClass: 0x7fd9e261d690>.
2016-04-11 15:56:27.264 aotulayoutDemo[7373:205889] obj3 = <SingleClass: 0x7fd9e261d690>.
2016-04-11 15:56:27.264 aotulayoutDemo[7373:205889] obj4 = <SingleClass: 0x7fd9e261d690>.
2016-04-11 15:56:27.264 aotulayoutDemo[7373:205889] 结束》》》

这里我们可以看到,获取到的对象都是一样的了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 目录 dispatch_once dispatch_once低负载特性 备注 参考文章 相信大家对dispatch...
    时间在改变阅读 5,573评论 0 6
  • 单例模式 什么是单例模式? 单例模式想一个大独裁者,他规定在他的国度里面,所有数据的访问和请求都得经过他,甚至你要...
    GitHubPorter阅读 4,873评论 0 4
  • 一、单例是什么?(aplɪˈkeɪʃ(ə)n 申请) 在 Foundation 和 Application Kit...
    甘哲157阅读 11,274评论 6 22
  • 在之前的帖子里聊过状态管理有多痛苦,有时这是不可避免的。一个状态管理的例子大家都很熟悉,那就是单例。使用Swift...
    Tank丶Farmer阅读 11,472评论 0 5
  • 标题源自我喜欢的一本同名书:《孤独的人,都要吃饱》,先安利。 ——题外话 【笼包】 一人食不可怕,放不下才可怕。 ...
    Mario梓欧_L阅读 1,833评论 0 2