Objective-c单例模式详解

转载自:http://www.jianshu.com/p/85618bcd4fee

单例模式出现以后,关于它的争执就一直存在。在开发项目中,有很多时候我们需要一个全局的对象,而且要保证全局有且仅有一份即可。没错,单例在这个时候就是最佳的选择,但是需要注意的是:在多线程的环境下也需要做好线程保护。其实系统已经有很多单例存在,例如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] 结束》》》

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



文/Jingege(简书作者)
原文链接:http://www.jianshu.com/p/85618bcd4fee
著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。
原文地址:https://www.cnblogs.com/CodingMann/p/5511938.html