GCD實(shí)現(xiàn)設(shè)計(jì)模式
在某個(gè)類里面實(shí)現(xiàn)GCD單粒設(shè)計(jì)模式
- 類的.h文件
@interface ZMJPerson : NSObject
+ (instancetype)sharedInstance;
@end
- 類的.m文件
// 實(shí)例變量私痹,當(dāng)前類
static id _instance;
// 重寫allocWithZone方法
+ (instancetype)allocWithZone:(struct _NSZone *)zone{
static dispatch_once_t onceToken;
// 該方法整個(gè)應(yīng)用程序只調(diào)用一次
dispatch_once(&onceToken, ^{
_instance = [super allocWithZone:zone];
});
return _instance;
}
+ (instancetype)sharedInstance{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [[self alloc] init];
});
return _instance;
}
// 保證每復(fù)制一個(gè)對(duì)象也是同一個(gè)內(nèi)存空間
- (id)copyWithZone:(NSZone *)zone{
return _instance;
}
宏定義封裝GCD單粒設(shè)計(jì)模式(1)
- 將實(shí)現(xiàn)單粒設(shè)計(jì)模式的代碼放到宏定義里面咒唆,并且專門搞個(gè).h文件存儲(chǔ)該宏定義卵贱,使用的之后直接導(dǎo)入頭文件即可窘茁,不必在每個(gè)類中實(shí)現(xiàn)單粒設(shè)計(jì)模式
- 注意:每行結(jié)尾需要添加\
// .h文件
#define ZMJSingletonH + (instancetype)sharedInstance;
// .m文件
#define ZMJSingletonM \
static id _instance;\
\
+ (instancetype)allocWithZone:(struct _NSZone *)zone{\
\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_instance = [super allocWithZone:zone];\
});\
return _instance;\
}\
\
+ (instancetype)sharedInstance{\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_instance = [[self alloc] init];\
});\
return _instance;\
}\
\
- (id)copyWithZone:(NSZone *)zone{\
return _instance;\
}
宏定義封裝GCD單粒設(shè)計(jì)模式(2)
- 如果希望每次有特有的類名怖糊,可以使用##拼接宏
// .h文件
#define ZMJSingletonH(name) + (instancetype)shared##name;
// .m文件
#define ZMJSingletonM(name) \
static id _instance;\
\
+ (instancetype)allocWithZone:(struct _NSZone *)zone{\
\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_instance = [super allocWithZone:zone];\
});\
return _instance;\
}\
\
+ (instancetype)shared##name{\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_instance = [[self alloc] init];\
});\
return _instance;\
}\
\
- (id)copyWithZone:(NSZone *)zone{\
return _instance;\
}
非GCD實(shí)現(xiàn)設(shè)計(jì)模式
就介紹怎么使用迅腔,其它宏定義保存跟上面一樣
ZMJPerson類的.h文件
@interface ZMJPerson : NSObject
+ (instancetype)sharedInstance;
@end
- ZMJPerson類的.h文件
static id _instance;
+ (instancetype)allocWithZone:(struct _NSZone *)zone{
// 同步鎖霜浴,防止多線程同時(shí)進(jìn)入
@synchronized(self){
if (_instance == nil) {
_instance = [super allocWithZone:zone];
}
}
return _instance;
}
+ (instancetype)sharedInstance{
@synchronized(self){
if (_instance == nil) {
_instance = [[self alloc] init];
}
}
return _instance;
}
- (id)copyWithZone:(NSZone *)zone{
return _instance;
}
注意點(diǎn)
- 一般當(dāng)兩個(gè)類有相同的屬性和方法够庙,我們會(huì)考慮將相同的部分抽取出來恭应,封裝到父類,讓這兩個(gè)類成為它的子類耘眨,但單粒設(shè)計(jì)模式不可以這樣做昼榛;
- 因?yàn)閟tart修飾的變量在內(nèi)存中只有一份內(nèi)存,如果單粒設(shè)計(jì)模式采用繼承的方式的話毅桃,所有的類共享一份內(nèi)存褒纲;
- 其實(shí)我們只要保證每一個(gè)類的對(duì)象只有一份內(nèi)存即可