首页 > 其他 > 详细

单例的设计模式()

时间:2015-10-22 12:09:04      阅读:291      评论:0      收藏:0      [点我收藏+]

单例的设计模式:

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

作用(为什么要用):

1,节省内存开销。

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

eg,[UIApplication sharedApplication];

[NSUserDefaults srandardUserDefaults];

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

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

怎么实现:

在MRC(非ARC)

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

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

1,重写allocWithZone(alloc方法)

2,重写init方法

3,重写release方法

4,重写retain方法

5,在写一个类方法

 

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就行了

技术分享

 

单例的设计模式()

原文:http://www.cnblogs.com/changjinping/p/4900170.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!