单例模式

来源:互联网 发布:海量数据存储 与读取 编辑:程序博客网 时间:2024/06/11 00:37

在iOS开发中,单例是在代码间共享数据而不需要手动传递参数的一种最有用的方法设计单例类的目的就是限制这个类只能创造一个对象。

实现单例模式有三个条件

1、类的构造方法是私有的

2、类提供一个类方法用于产生对象

3、类中有一个私有的自己对象


针对于这三个条件,OC中都是可以做到的

1、类的构造方法是私有的

我们只需要重写allocWithZone方法,让初始化操作只执行一次

2、类提供一个类方法产生对象

这个可以直接定义一个类方法

3、类中有一个私有的自己对象

我们可以在.m文件中定义一个属性即可



一般情况下,可能我们写的单例模式是这样的:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#import<foundation /foundation.h>
 
@interfaceSingleton : NSObject
 
+(instancetype) shareInstance ;
 
@end
 
 
 
#import"Singleton.h"
 
@implementationSingleton
 
staticSingleton* _instance = nil;//不能让外部访问,同时放在静态块中的 
 
+(instancetype) shareInstance
{
    staticdispatch_once_t onceToken ;
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc] init] ;
    }) ;
     
    return_instance ;
}
 
@end

我们定义了一个静态变量叫做shareInstance,它在shareInstance方法中只会被实例化一次。通过GCD的dispath_once方法,

我们确保shareInstance方法只会被创建一次,这是线程安全的。

但是,如果你不想用GCD,也可以这样实现shareInstance方法:


非-GCD 代码


+ (id)shareInstance {


    @synchronized(self) {


       if (shareInstance == nil)


           shareInstance = [[self alloc] init];


    }


    return shareInstance;

}


这样调用单例对象:


Singleton * singleton = [Singleton shareInstance]





当我们调用shareInstance方法时获取到的对象是相同的,但是当我们通过alloc和init来构造对象的时候,得到的对象却是不一样的。


那么问题就来了,我们通过不同的途径得到不同的对象,显然是不行的。我们必须要确保对象的唯一性,所以我们就需要封锁用户通过alloc和init以及copy来构造对象这条道路。

我们知道,创建对象的步骤分为申请内存(alloc)、初始化(init)这两个步骤,我们要确保对象的唯一性,因此在第一步这个阶段我们就要拦截它。当我们调用alloc方法时,

oc内部会调用allocWithZone这个方法来申请内存,我们覆写这个方法,然后在这个方法中调用shareInstance方法返回单例对象,这样就可以达到我们的目的。

拷贝对象也是同样的原理,覆写copyWithZone方法,然后在这个方法中调用shareInstance方法返回单例对象。看代码吧:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#import"Singleton.h"
 
@implementationSingleton
 
staticSingleton* _instance = nil;
 
+(instancetype) shareInstance
{
    staticdispatch_once_t onceToken ;
    dispatch_once(&onceToken, ^{
        _instance = [[superallocWithZone:NULL] init] ;
    }) ;
     
    return_instance ;
}
 
+(id) allocWithZone:(struct _NSZone *)zone
{
    return[Singleton shareInstance] ;
}
 
-(id) copyWithZone:(struct _NSZone *)zone
{
    return[Singleton shareInstance] ;
}
 
@end


1 0