单例的设计模式()

单例的设计模式:

什么是单例设计模式:它可以保证某个类创建出来的对象永远只有一个。

作用(为什么要用):

1,节省内存开销。

2,如果有一些数据,整个程序中都用得上,只需要使用同一份资源即可(保证大家访问的数据是相同的,一致的)。

eg,[UIApplication sharedApplication];

[NSUserDefaults srandardUserDefaults];

[UIDevice currentDevice];都是用了单例设计模式。

3,一般来说,工具类设计为单例模式比较合适。(声音播放)

怎么实现:

在MRC(非ARC)

利用MJSoundTool创建出来的对象是同一个,保证永远只分配一块。

alloc方法内部会调用allocWithZone(Zone为空间)

1,定义一个全局变量并初始化为nil;

2,重写allocWithZone(alloc方法)

3,重写init方法

4,重写release方法

5,重写retain方法

6,在写一个类方法

 

static Singleton * instance = nil;

 

+(instancetype)allocWithZone:(struct _NSZone *)zone

{

    //    @synchronized (self)

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        if (instance==nil) {

            // instance=[super allocWithZone:<#zone#>];

        }

    });

    

    return instance;

}

-(instancetype)init

{

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        instance = [super init];

    });

    return instance;

}

//不销毁对象

-(oneway void)release

{

    

}

//不能增加

-(instancetype)retain

{

    return self;

}

-(NSUInteger)retainCount

{

    return 1;

}

+(instancetype)danli

{

    return [[Singleton alloc]init];

}

在ARC中,去掉release retain  retainCount就行了

 

posted @ 2015-10-22 10:51  知至  阅读(171)  评论(0编辑  收藏  举报