首页 > 移动平台 > 详细

ios 单例模式(懒汉式)

时间:2015-10-04 15:49:32      阅读:777      评论:0      收藏:0      [点我收藏+]

1. 单例模式的作用

  • 可以保证在程序运行过程,一个类只有一个实例,而且该实例易于供外界访问
  • 从而方便地控制了实例个数,并节约系统资源

2. 单例模式的使用场合

  • 在整个应用程序中,共享一份资源(这份资源只需要创建初始化1次)

3. ARC中,单例模式的实现

在.m中保留一个全局的static的实例

 

1.ARC

@interface HMDataTool : NSObject

+ (instancetype)sharedDataTool;

@end

 

@implementation HMDataTool

// 用来保存唯一的单例对象

static id _instace;

 //重载了allocWithZone:,保持了从sharedInstance方法返回的单例对象,使用者哪怕使用alloc时也会返回唯一的 实例(alloc方法中会先调用allocWithZone:创建对象)。而retain等内存管理的函数也被重载了,这样做让我们有了把 Singleton类变得“严格”了。

 

+ (id)allocWithZone:(struct _NSZone *)zone

{

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        _instace = [super allocWithZone:zone];

    });

    return _instace;

}

 

+ (instancetype)sharedDataTool

{

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        _instace = [[self alloc] init];

    });

    return _instace;

}

 

- (id)copyWithZone:(NSZone *)zone

{

    return _instace;

}

@end

 

2.非ARC

@interface HMDataTool : NSObject

+ (instancetype)sharedDataTool;

@end

 

@implementation HMDataTool

// 用来保存唯一的单例对象

static id _instace;

 

+ (id)allocWithZone:(struct _NSZone *)zone

{

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        _instace = [super allocWithZone:zone];

    });

    return _instace;

}

 

+ (instancetype)sharedDataTool

{

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        _instace = [[self alloc] init];

    });

    return _instace;

}

 

- (id)copyWithZone:(NSZone *)zone

{

    return _instace;

}

 

- (oneway void)release {

   

}

 

- (id)retain {

    return self;

}

 

- (NSUInteger)retainCount {

    return 1;

}

 

- (id)autorelease {

    return self;

}

@end

 
 
 
 

ios 单例模式(懒汉式)

原文:http://www.cnblogs.com/zhongxuan/p/4854547.html

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