單例模式的核心承諾很簡單:一個類別永遠只會有一個實例,並對外提供一個全域的存取點。NSUserDefaults、UIApplication、各類管理器幾乎都採用這個模式,因為它們代表的是「系統中的唯一資源」。
要正確實作,必須處理兩個問題:
alloc/copy 等途徑另外生出實例,否則單例的承諾就被破壞了。#import <Foundation/Foundation.h> @interface Singleton : NSObject + (Singleton *)sharedInstance; @end
#import "Singleton.h"
@implementation Singleton
static Singleton *sharedSingleton = nil;
+ (Singleton *)sharedInstance {
if (sharedSingleton == nil) {
// 寫法一:一般配置
// sharedSingleton = [[Singleton alloc] init];
// 寫法二:先呼叫 super 的 allocWithZone,避開自己重載的版本
// 之所以用 super 而非 self,是因為 self 已重載 allocWithZone
// allocWithZone 內部實際呼叫的是 NSAllocateObject
// sharedSingleton = [[super allocWithZone:NULL] init];
// 寫法三:直接呼叫底層配置函式
// 參數一:類別;參數二:額外的實例變數位元組數(恆為 0);參數三:記憶體區域(NULL 為預設)
// 之所以選寫法三,是因為無論 Singleton 本身或其子類呼叫,都能正確處理
sharedSingleton = [NSAllocateObject([self class], 0, NULL) init];
}
return sharedSingleton;
}
// 重載 allocWithZone:,使 alloc 不會產生新實例
// alloc 內部呼叫的就是 allocWithZone:NULL
+ (id)allocWithZone:(struct _NSZone *)zone {
return [[self sharedInstance] retain];
}
// 重載 copyWithZone:,避免 copy 複製出新實例
- (id)copyWithZone:(NSZone *)zone {
return self;
}
// 以下四個記憶體管理方法全部改成「什麼都不做」,讓引用計數失去意義
- (id)retain {
return self;
}
- (NSUInteger)retainCount {
return NSUIntegerMax;
}
- (void)release {
// 刻意留空
}
- (id)autorelease {
return self;
}
@end
單例的破壞通常不是刻意的,而是某段程式碼順手寫了 [[Singleton alloc] init] 或 [singleton copy]。把 allocWithZone: 與 copyWithZone: 都導向同一個實例,等於從源頭堵住這些途徑;而讓 retain/release/autorelease 空轉,則確保它不會被意外釋放。
需要留意的是,retainCount 回傳 NSUIntegerMax 只是一種慣例表達,蘋果本身就不建議依賴 retainCount 做任何判斷。
如果你使用的是 ARC(今日的標準情況),上述大部分重載都不再需要,實作可以精簡成 dispatch_once 版本,這也是目前最推薦的寫法:
+ (Singleton *)sharedInstance {
static Singleton *sharedSingleton = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedSingleton = [[self alloc] init];
});
return sharedSingleton;
}
dispatch_once 由系統保證在執行緒安全的前提下只執行一次,程式碼意圖清楚,也不需手動處理記憶體。在 Swift 中更簡單,宣告一個 static 常數即可:
final class Singleton {
static let shared = Singleton()
private init() {}
}
private init() 這個寫法很關鍵——它把初始化方法收為私有,從語言層面杜絕外部另建實例的可能,比在 Objective-C 中靠重載來「攔截」要來得可靠。