您的位置:首页 > 其它

单例

2016-02-20 22:00 260 查看
(1)单例模式的作用 :可以保证在程序运行过程,一个类只有一个实例,而且该实例易于供外界访问,从而方便地控制了实例个数,并节约系统资源。

(2)单例模式的使用场合:在整个应用程序中,共享一份资源(这份资源只需要创建初始化1次),应该让这个类创建出来的对象永远只有一个。

(3)单例模式在ARC\MRC环境下的写法有所不同,需要编写2套不同的代码

创建单例的步骤

1. 定义一个全局的静态变量,用来记录“第一次”被实例化出来的对象

重写allocWithZone方法,此方法是为对象分配内存空间必须会被调用的一个方法!

因此,在此方法中使用”dispatch_once”,能够保证在多线程中,_instance也只能被“分配”一次空间

定义一个sharedXXX“类”方法,方便其他使用单例的对象调用此单例

在此方法中,同样使用”dispatch_once”,保证使用类方法调用的对象,只会被初始化一次!

注释:如果不考虑copy & MRC,以上三个步骤即可!

如果要支持copy,则需要

1> 遵守NSCopying协议

2> 在copyWithZone方法中,直接返回_instance

#import <Foundation/Foundation.h>

@interface NetworkTool : NSObject
//单例实例化方法
+ (instancetype)shareNetworkTool;
@end

#import "NetworkTool.h"
@implementation NetworkTool
//单例存在静态区
static id _instance;

+ (instancetype)shareNetworkTool {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [[self alloc] init];
});
return _instance;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [super allocWithZone:zone];
});
return _instance;
}

- (id)copyWithZone:(NSZone *)zone {
return _instance;
}

/**
*  MRC 情况下需要添加的方法
*/
//__has_feature(objc_arc)判断arc条件(arc&mrc 混编)
#if !__has_feature(objc_arc)
- (oneway void)release {
}

- (instancetype)retain {
return _instance;
}

- (instancetype)autorelease {
return _instance;
}

- (NSUInteger)retainCount {
return 1;
}
#endif
@end


另附上单例宏

4000

//在 single.h 文件中创建宏
#define single_h(name) + (instancetype)share##name;

#if __has_feature(objc_arc)
//ARC
#define single_m(name) static id _instance;\
\
+ (instancetype)share##name {\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_instance = [[self alloc] init];\
});\
return _instance;\
}\
\
+ (instancetype)allocWithZone:(struct _NSZone *)zone {\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_instance = [super allocWithZone:zone];\
});\
return _instance;\
}\
\
- (id)copyWithZone:(NSZone *)zone {\
return _instance;\
}
#else
//MRC
#define single_m(name) static id _instance;\
\
+ (instancetype)share##name {\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_instance = [[self alloc] init];\
});\
return _instance;\
}\
\
+ (instancetype)allocWithZone:(struct _NSZone *)zone {\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_instance = [super allocWithZone:zone];\
});\
return _instance;\
}\
\
- (id)copyWithZone:(NSZone *)zone {\
return _instance;\
}\
- (oneway void)release {\
}\
\
- (instancetype)retain {\
return _instance;\
}\
\
- (instancetype)autorelease {\
return _instance;\
}\
\
- (NSUInteger)retainCount {\
return 1;\
}

#endif


使用方法

#import <Foundation/Foundation.h>
#import "Single.h"
@interface PlayTool : NSObject

single_h(PlayTool);

@end

#import "PlayTool.h"

@implementation PlayTool

single_m(PlayTool)

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