標籤:
一、定義
- 單例模式:保證一個類僅有一個執行個體,並提供一個訪問它的全域訪問點。
如何保證只能建立一個執行個體
二、使用
- 類只能有一個執行個體,而且必須從一個為人熟知的訪問點對其進行訪問
- 這個唯一的執行個體只能通過子類化進行擴充,而且擴充的對象不會破壞用戶端代碼
三、代碼
- 方法一
1 #import "Singleton.h" 2 3 @implementation Singleton 4 5 static Singleton * shared = nil; 6 7 + (Singleton *)sharedInstance 8 { 9 static dispatch_once_t once;10 dispatch_once(&once, ^{11 shared = [[super allocWithZone:NULL] init];12 });13 14 return shared;15 }16 17 + (instancetype)allocWithZone:(struct _NSZone *)zone18 {19 return [self sharedInstance];20 }21 22 @end
調用:
1 Singleton * single = [[Singleton alloc] init]; 2 NSLog(@"%@", single); 3 4 Singleton * sing = [Singleton sharedInstance]; 5 NSLog(@"%@", sing); 6 7 Singleton * single1 = [[Singleton alloc] init]; 8 NSLog(@"%@", single1); 9 10 Singleton * sing1 = [Singleton sharedInstance];11 NSLog(@"%@", sing1);
輸出結果:
這樣,當我們調用alloc的時候,會自動調用+ (instancetype)allocWithZone:(struct _NSZone *)zone方法,調用這個方法的時候,就會調用sharedInstance方法,所以這樣不管什麼時候使用這個類,最終都是由sharedInstance返回的,而且,sharedInstance方法,只初始化該對象一次,所以返回的地址都是一樣的。
1 #import "Singleton.h" 2 3 @implementation Singleton 4 5 static Singleton * shared = nil; 6 7 + (Singleton *)sharedInstance 8 { 9 if(shared == nil){10 shared = [[self alloc] init];11 }12 return shared;13 }14 15 + (instancetype)allocWithZone:(struct _NSZone *)zone16 {17 static dispatch_once_t once;18 dispatch_once(&once, ^{19 shared = [[super allocWithZone:zone] init];20 });21 22 return shared;23 }24 25 @end
方法一和方法二,執行的效果是一樣的,只是函數的執行數序是不同的,方法一不管調用哪個方法,最後調用的一個是sharedInstance,而方法二,不管調用哪一個函數,最終調用的是allocWithZone。其實底層實現都是一樣的,最終都由[[super allocWithZone:zone] init]返回一個地址給static對象。
ios設計模式——單例模式