iOS 單例模式 (設計模式一)

來源:互聯網
上載者:User

iOS 單例模式 (設計模式一)

單例模式是一種常用的軟體設計模式。在它的核心結構中只包含一個被稱為單例類的特殊類。通過單例模式可以保證系統中一個類只有一個執行個體而且該執行個體易於外界訪問,從而方便對執行個體個數的控制並節約系統資源。如果希望在系統中某個類的對象只能存在一個,單例模式是最好的解決方案。

主要優點:

提供了對唯一執行個體的受控訪問。 由於在系統記憶體中只存在一個對象,因此可以節約系統資源,對於一些需要頻繁建立和銷毀的對象單例模式無疑可以提高系統的效能。 允許可變數目的執行個體。

主要缺點:

由於單利模式中沒有抽象層,因此單例類的擴充有很大的困難。 單例類的職責過重,在一定程度上違背了“單一職責原則”。 濫用單例將帶來一些負面問題,如為了節省資源將資料庫連接池對象設計為的單例類,可能會導致共用串連池對象的程式過多而出現串連池溢出;如果執行個體化的對象長時間不被利用,系統會認為是垃圾而被回收,這將導致對象狀態的丟失。 給HSCommonTool類設定單例模式
#import @interface HSCommonTool : NSObject+ (instancetype)sharedCommonTool;@end
#import HSCommonTool.h@interface HSCommonTool()@end@implementation HSCommonTool// 定義一個靜態變數static HSCommonTool *_commonTool;// 重寫allocWithZone方法,alloc內部調用次方法+ (instancetype)allocWithZone:(struct _NSZone *)zone{    // 設定allocWithZone只執行一次    static dispatch_once_t onceToken;    dispatch_once(&onceToken, ^{        _commonTool = [super allocWithZone:zone];    });    return _commonTool;}//  copy對象時,調用此方法- (id)copyWithZone:(nullable NSZone *)zone{    return _commonTool;}// 寫個類方法,方便外界調用+ (instancetype)sharedCommonTool{    static dispatch_once_t onceToken;    dispatch_once(&onceToken, ^{        _commonTool = [[self alloc] init];    });    return _commonTool;}@end
單例模式的封裝 - HSSingleton.h
// .h檔案#define HSGSingletonH(name) + (instancetype)shared##name;// .m檔案#define HSGSingletonM(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; }

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.