前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >几种单例

几种单例

作者头像
用户1451823
发布2018-09-13 17:24:09
2960
发布2018-09-13 17:24:09
举报

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://cloud.tencent.com/developer/article/1338208

单例

单例:Singleton pattern。就是只有一个实例,不管实例化多少个对象,对象都是唯一的(可以通过打印其地址证明)。

下面就是一些单例的代码,不是很全,后面接触到新的还会继续补充。

1.普通创建单例的方法:

利用类方法创建单例,首先是类方法的声明(就是普通类方法的声明,不必多说)。

代码:

#import<Foundation/Foundation.h>

@interface StudentManager :NSObject

+(StudentManager *)shareInstance;

@end                                                               

重点是单例的创建,也就是这个类方法的实现。

代码:

#import"StudentManager.h"

staticStudentManager * student;

@implementation StudentManager

+(StudentManager *)shareInstance

{

if (student ==nil) {

student = [StudentManageralloc init];

    }

returnstudent;

}

@end

这样单例就创建好了,当我们用这个类方法来创建对象的时候,哪怕是创建再多的对象得到的对象都是唯一的,也就是单例。至于为什么要用单例呢,大家可以上网区查查,有比较全面、详细的解释。一般当系统中希望某个类的对象只有一个的时候,我们一般都会用到单例。

2.利用dispatch创建单例:

也是利用了一个类方法,声明和前面的是一样的,就不在赘述了。

实现代码:

#import"StudentManager.h"

@implementation StudentManager

+(StudentManager *)shareInstance

{

staticStudentManager * studentManager;

staticdispatch_once_t oneToken;

dispatch_once(&oneToken, ^{

studentManager = [StudentManageralloc init];

});

return studentManager;

}

@end

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2015年09月08日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档