Objective-C之单例设计模式
2015-09-08 22:36
411 查看
1.单例设计模式介绍
任何时间,任何地点, 内存中都只有一个对象实例1>懒汉式(尽可能晚的创建单例对象),在第一次使用时(第一次调用sharedXxx方法时)创建单例对象。
2>锇汉式(尽可能早的创建单例对象),程序一开始就创建一个单例对象。
实现方式,重写类方法+ (void)load,在类被加载到运行时时,立刻执行。(这个方法只会被执行一次)
2. 实现思路:
1>为类增加一个static id instance;变量 //改变变量的生命周期, 是变量一直存在2> 重写类方法allocWithZone:
3> 封装一个sharedInstance方法,在该方法中调用alloc方法创建件对象。
3.代码演示
//SingleInstanceTool.h#import <Foundation/Foundation.h> @interface SingleInstanceTool : NSObject <NSCopying> @property (nonatomic, assign, readwrite) int num;// 数量 @property (nonatomic, copy, readwrite) NSString *text;// 文本 //提供接入点 + (instancetype)shareInstance; @end
//SingleInstaceTool.m
#import "SingleInstanceTool.h" //创建一个全局变量, 并保存以前的值 static SingleInstanceTool *instance = nil; @implementation SingleInstanceTool +(instancetype)shareInstance{ //判断 if (instance == nil) { instance = [[SingleInstanceTool alloc] init]; // //设置属性值 // instance.num = 24; // instance.text = @"zhaofei"; // return instance; } return instance; } - (id)copyWithZone:(NSZone *)zone{ return self; } //注意在多线程环境下要使用@synchronized(self){} + (instancetype)allocWithZone:(struct _NSZone *)zone{ @synchronized(self){ if (instance == nil) { instance = [super allocWithZone:zone]; //设置属性值 instance.num = 24; instance.text = @"zhaofei"; return instance; } } return instance; }
//MRC模式下,需要重写一下三个方法, 保证单例对象不会被释放 //当对instance进行retain操作时, 直接返回instance, 不进行计数器加1 -(instancetype)retain{ return self; } //当对instance进行release操作时, 不做任何操作 -(oneway void)release{ } //当要查看instance的计数器时, 直接返回一个最大数 -(NSUInteger)retainCount{ return NSUIntegerMax; } @end
相关文章推荐
- objective-c中的extern static const总结
- Objective-C之深拷贝与浅拷贝
- Objective-C之深拷贝与浅拷贝
- dictionaryWithObjectsAndKeys
- 有趣Web之Json(四)---json与(Object/List/Map)相互转化
- 浅谈 Objective-C 指针和 Swift2
- Objective-C基础知识之(四):实例变量的可变度、初始化方法的声明、self和super的具体应用
- Objective-C基础知识之(二):方法的类型、setter方法、getter方法、初始化方法、其他方法
- Objc中block的实现
- scala中 object 和 class的区别
- Objective-C语法之动态类型(isKindOfClass, isMemberOfClass,id)等
- UIKit各类Object继承关系
- javascript Object Pool 对象池
- delphi开发activexObject传递参数的两种方法:
- Objective-C 词典与集合
- POJ 3241 Object Clustering 平面曼哈顿最小生成树
- IOS 零基础到就业 --- 最简单的Objective-C程序
- [Object-C] 导航栏 title 字体颜色的修改
- C#的LINQ to Object
- C语言函数指针和Objective-c中的block