您的位置:首页 > 移动开发 > Objective-C

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: