單例模式(掌握)
- 單例模式
- 作用
- 可以保證在程序運行過程中,一個類只有一個實例,而且該實例易于供外界訪問
- 方便地控制了實例個數,并節約系統資源
- 使用場合
- 在整個應用程序中,共享一份資源(這個資源只需要創建初始化一次)
- 網絡請求工具類
- NSFileManager defaultManager
- UIApplication sharedApplication
- 單例模式實現
- 1.創建一個繼承NSObject的圖片下載工具類
- 2.工具類創建出來的對象永遠都是同一個對象
- alloc]init
- 重寫alloc方法
- 類方法
- alloc方法內部會調用allocWithZone:
- allocWithZone:
- 重寫allocWithZone:
- 定義靜態變量,分配存儲空間
- 3.提供一個類方法,方便外界訪問(身份標識)
- 規范:share+類名 | share | default |manager
創建一個靜態變量:分配存儲空間
static DownloadTool *_instance;
@synchronized(self){
if(_instance == nil){
_instance = [super allocWithZone:zone];
}
return _instance
}
提供一個類方法
規范:share+類名 | share | default |manager
+(instancetype)shareDownloadTool{
return [[self alloc]init];
}
- 問題:如何讓變量私有化,作用域只在當前類,外部不可以使用
- 問題:異步函數+全局并發隊列,在block里面創建工具類,開多條線程并發執行任務,比如開線程A/B,第一次Ainstance沒有值,B進來instance也沒有值,分配了兩次存儲空間。
- 加同步鎖,@synchronized(self){}
- GCD的一次性代碼
- dispatch_once(&onceToken,^{_instance = [super allocWithZone:zone];})
- 4.單例模式實現更嚴謹需要重寫copy|mutablecopy方法
- 遵守<NSCoping,NSMutableCoping>
- 調用copy方法,需要對象調用
-(id)copyWithZone:(NSZone*)zone{
return _instance;
}
-(id)mutableCopyWithZone:(NSZone*)zone{
return _instance;
}
簡潔單例模式(不完全單例模式)
+(instancetype)shareTool{
static Tool * _instance;
static dispatch_once_t onceToken;
dispatch_once(&onceToken,^{
_instance = [[self alloc]init];
})
return _instance
}
- 使用前提
- 開發中,如果時間比較緊張壓力比較大,可以使用這種方法,如果是獨自開發,也可以使用這種方式;但是,如果是多人開發,建議使用完整的單例模式實現方式
最后編輯于 :
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。