單例

單例模式.jpg

在項(xiàng)目中我們經(jīng)常會(huì)用到單例類,覺得很方便,但是其弊端也很明顯:單例類的職責(zé)過重,在一定程度上違背了“單一職責(zé)原則”。因?yàn)閱卫惣瘸洚?dāng)了工廠角色,提供了工廠方法,同時(shí)又充當(dāng)了產(chǎn)品角色,包含一些業(yè)務(wù)方法,將產(chǎn)品的創(chuàng)建和產(chǎn)品的本身的功能融合到一起。

如何寫一個(gè)安全的單例類呢?看聲明文件

#import <Foundation/Foundation.h>

@interface DanLi : NSObject<NSCopying,NSMutableCopying>

//單例類
+ (instancetype)sharedInstance;
@end

再看實(shí)現(xiàn)文件

#import "DanLi.h"

@implementation DanLi

static DanLi *instance = nil;
+ (instancetype)sharedInstance {
    return [[self alloc]init];
}

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

- (id)copyWithZone:(struct _NSZone *)zone {
    return [DanLi sharedInstance];
}
-(instancetype)mutableCopyWithZone:(NSZone *)zone{
    return [DanLi sharedInstance];
}

//new方法不需要重寫

- (DanLi *)init {
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
         if(!instance){
       instance = [super init];
    }
    
    return instance;
}
@end
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容