OC基础(27)
2015-12-03 22:19
369 查看
单例设计模式
【理解】简单的单例模式实现
单例模式的意图是是的类的对象成为系统中唯一的实例,供一个访问点,供客户类 共享资源。
什么情况下使用单例?
1、类只能有一个实例,而且必须从一个为人熟知的访问点对其进行访问,比如工厂方 法。
2、这个唯一的实例只能通过子类化进行扩展,而且扩展的对象不会破坏客户端代码。
单例设计模式的要点:
1) 某个类只能有一个实例。
2)他必须自行创建这个对象
3)必须自行向整个系统供这个实例;
4)为了保证实例的唯一性,我们必须将
5)这个方法必须是一个静态类
单例设计模式
本小节知识点:
【理解】单例模式概念【理解】简单的单例模式实现
1.单例模式概念
什么是单例模式:(Singleton)单例模式的意图是是的类的对象成为系统中唯一的实例,供一个访问点,供客户类 共享资源。
什么情况下使用单例?
1、类只能有一个实例,而且必须从一个为人熟知的访问点对其进行访问,比如工厂方 法。
2、这个唯一的实例只能通过子类化进行扩展,而且扩展的对象不会破坏客户端代码。
单例设计模式的要点:
1) 某个类只能有一个实例。
2)他必须自行创建这个对象
3)必须自行向整个系统供这个实例;
4)为了保证实例的唯一性,我们必须将
5)这个方法必须是一个静态类
2.简单的单例模式实现
#define interfaceSingleton(name) +(instancetype)share##name #if __has_feature(objc_arc) // ARC #define implementationSingleton(name) \ + (instancetype)share##name \ { \ name *instance = [[self alloc] init]; \ return instance; \ } \ static name *_instance = nil; \ + (instancetype)allocWithZone:(struct _NSZone *)zone \ { \ static dispatch_once_t onceToken; \ dispatch_once(&onceToken, ^{ \ _instance = [[super allocWithZone:zone] init]; \ }); \ return _instance; \ } \ - (id)copyWithZone:(NSZone *)zone{ \ return _instance; \ } \ - (id)mutableCopyWithZone:(NSZone *)zone \ { \ return _instance; \ } #else // MRC #define implementationSingleton(name) \ + (instancetype)share##name \ { \ name *instance = [[self alloc] init]; \ return instance; \ } \ static name *_instance = nil; \ + (instancetype)allocWithZone:(struct _NSZone *)zone \ { \ static dispatch_once_t onceToken; \ dispatch_once(&onceToken, ^{ \ _instance = [[super allocWithZone:zone] init]; \ }); \ return _instance; \ } \ - (id)copyWithZone:(NSZone *)zone{ \ return _instance; \ } \ - (id)mutableCopyWithZone:(NSZone *)zone \ { \ return _instance; \ } \ - (oneway void)release \ { \ } \ - (instancetype)retain \ { \ return _instance; \ } \ - (NSUInteger)retainCount \ { \ return MAXFLOAT; \ } #endif
相关文章推荐
- if 语句练习 身高体重问题
- 理解长短期记忆网络(LSTM NetWorks)
- 黑马程序员——Java笔记——String类的面试题
- HDU 1016Presentation Error
- 国外程序员整理的Java资源大全
- jqueryHTML相关方法
- OC基础(26)
- 原型设计(“留拍”Axure整体操作过程)
- CoffeeScript ------ 问号
- ZABBIX安装配置过程
- Quora上关于P, NP, NP-complete, and NP-hard问题的解答
- R语言数据处理(一)
- Mac使用技巧
- windows10安装ubuntu15.10后只有ubuntu启动项
- 闭包(1)初识闭包
- 用文章和视频的app例子简介React-Native
- 通俗理解马尔科夫链
- 在MAC下面用 eclipse调试android 6.0 framework
- [置顶] struts2笔试面试
- setTimeout()&&setInterval()实例