Skip to content

Instantly share code, notes, and snippets.

@zhangkn
Created May 4, 2018 07:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhangkn/9f90f6e4f32e104a18b3473b2e40cf4f to your computer and use it in GitHub Desktop.
Save zhangkn/9f90f6e4f32e104a18b3473b2e40cf4f to your computer and use it in GitHub Desktop.
单例模式
// 单例模式的作用
可以保证在程序运行过程,一个类只有一个实例,而且该实例易于供外界访问;从而方便地控制了实例个数,并节约系统资源
// 单例模式的使用场合
在整个应用程序中,共享一份资源(这份资源只需要创建初始化1次)
//1、 单例模式在ARC\MRC环境下的写法有所不同,需要编写2套不同的代码
// 1)可以用宏判断是否为ARC环境
#if __has_feature(objc_arc)
// ARC
#else
// MRC
#endif
// 一、单例模式 - ARC
// ARC中,单例模式的实现
// 1)在.m中保留一个全局的static的实例
static id _instance;
//2) 重写allocWithZone:方法,在这里创建唯一的实例(注意线程安全)
+ (id)allocWithZone:(struct _NSZone *)zone {
if (_instance == nil) { // 防止频繁加锁
@synchronized(self) {
if (_instance == nil) { // 防止创建多次
_instance = [super allocWithZone:zone];
}
}
}
return _instance;
}
//3) 提供1个类方法让外界访问唯一的实例
+ (instancetype)sharedMusicTool {
if (_instance == nil) { // 防止频繁加锁
@synchronized(self) {
if (_instance == nil) { // 防止创建多次
_instance = [[self alloc] init];
}
}
}
return _instance;
}
// 4)实现copyWithZone:方法
- (id)copyWithZone:(struct _NSZone *)zone {
return _instance;
}
// 二、单例模式 – 非ARC
// 非ARC中(MRC),单例模式的实现(比ARC多了几个步骤)
// 实现内存管理方法
- (id)retain { return self; }
- (NSUInteger)retainCount { return 1; }
- (oneway void)release {}
- (id)autorelease { return self; }
// 三、>pod KNIosCommonTool,整合之后的代码
//
// HSSingleton.h
//
// Created by devzkn on 5/4/16.
//
#ifndef HSSingleton_h
#define HSSingleton_h
//头文件的单例内容
#define HSSingletonH(classname) +(instancetype)share##classname
//.m文件的单例代码
#if __has_feature(objc_arc)
#define HSSingletonM(classname) \
static id _instance;\
+(instancetype)share##classname{\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_instance = [[self alloc]init];\
});\
return _instance;\
}\
- (id)copyWithZone:(NSZone *)zone{\
return _instance;\
}\
+ (instancetype)allocWithZone:(struct _NSZone *)zone{\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_instance = [super allocWithZone:zone];\
});\
return _instance;\
}
#else
#define HSSingletonM(classname) \
static id _instance;\
+(instancetype)share##classname{\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_instance = [[self alloc]init];\
});\
return _instance;\
}\
- (id)copyWithZone:(NSZone *)zone{\
return _instance;\
}\
+ (instancetype)allocWithZone:(struct _NSZone *)zone{\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_instance = [super allocWithZone:zone];\
});\
return _instance;\
}\
- (oneway void)release{\
}\
- (instancetype)retain{\
return self;\
}\
- (NSUInteger)retainCount{\
return 1;\
}\
- (instancetype)autorelease{\
return self;\
}
#endif
#endif /* HSSingleton_h */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment