單例模式說穿了就是:一個類只有一個實例,並透過一個全域存取點取得它。實例通常在第一次被請求時才建立,也就是所謂的延遲載入。
Apple 大量使用這個模式:[NSUserDefaults standardUserDefaults]、[UIApplication sharedApplication]、[UIScreen mainScreen]、[NSFileManager defaultManager] 全都回傳單一物件。
你可能會想:記憶體和程式碼都很便宜,為什麼要計較一個類有幾個實例?確實,多實例在記憶體上成本不高,但問題往往不在記憶體,而在狀態一致性。舉例來說,日誌類如果有多份實例,你想一次寫入多個日誌檔時才用得上;否則一份就夠。全域設定檔更是如此——集中管理一份設定,遠比同時修改多份設定檔安全得多。

圖中是一個日誌類,有一個靜態屬性(唯一實例)與兩個方法:sharedInstance 與 init。客戶端發送 sharedInstance 訊息時,若 instance 尚未初始化就先建立;之後每次呼叫都直接回傳同一個物件。這個邏輯最終只會產生一個實例。
在專案的 API 資料夾中建立一個 Objective-C 類,命名為 LibraryAPI,父類選 NSObject。
// LibraryAPI.h @interface LibraryAPI : NSObject + (LibraryAPI *)sharedInstance; @end
// LibraryAPI.m
+ (LibraryAPI *)sharedInstance {
// 1. 靜態變數保存實例,確保全域可用
static LibraryAPI *_sharedInstance = nil;
// 2. 確保初始化程式碼只執行一次
static dispatch_once_t oncePredicate;
// 3. 用 GCD 的 dispatch_once 完成初始化——這是單例的關鍵
dispatch_once(&oncePredicate, ^{
_sharedInstance = [[LibraryAPI alloc] init];
});
return _sharedInstance;
}
這段短程式碼做了三件事:宣告靜態變數持有實例;宣告 dispatch_once_t 保證初始化只跑一次;用 Grand Central Dispatch 執行初始化的 block。此後再呼叫 sharedInstance,block 內的程式碼不會再執行,直接回傳先前建立的實例。
建立 PersistencyManager 類,同樣放在 API 資料夾。
// PersistencyManager.h #import "Album.h" @interface PersistencyManager : NSObject - (NSArray *)getAlbums; - (void)addAlbums:(Album *)album atIndex:(int)index; - (void)deleteAlbumAtIndex:(int)index; @end
用 class extension 加入私有狀態,這是宣告私有屬性與方法的常見手法,類別外部看不到:
// PersistencyManager.m
@interface PersistencyManager () {
NSMutableArray *albums;
}
初始化時塞入一些假資料:
- (id)init {
self = [super init];
if (self) {
albums = [NSMutableArray arrayWithArray:@[
[[Album alloc] initWithTitle:@"Best of Bowie" artist:@"David Bowie" coverUrl:@"..." year:@"1992"],
[[Album alloc] initWithTitle:@"It's My Life" artist:@"No Doubt" coverUrl:@"..." year:@"2003"],
[[Album alloc] initWithTitle:@"Nothing Like The Sun" artist:@"Sting" coverUrl:@"..." year:@"1999"],
[[Album alloc] initWithTitle:@"Staring at the Sun" artist:@"U2" coverUrl:@"..." year:@"2000"],
[[Album alloc] initWithTitle:@"American Pie" artist:@"Madonna" coverUrl:@"..." year:@"2000"]
]];
}
return self;
}
三個操作方法:
- (NSArray *)getAlbums {
return albums;
}
- (void)addAlbum:(Album *)album atIndex:(int)index {
if (albums.count >= index)
[albums insertObject:album atIndex:index];
else
[albums addObject:album];
}
- (void)deleteAlbumAtIndex:(int)index {
[albums removeObjectAtIndex:index];
}
Objective-C 的方法在本質上都是公開的,加上語言本身是動態型別,任何類都能互相發送訊息;而 Cocoa 使用引用計數管理物件生命週期。這些特性決定了 OC 的單例寫法與 Java 略有不同,而且 ARC 與 MRC 環境下需要兩套程式碼,可以用巨集判斷:
#if __has_feature(objc_arc) // ARC #else // MRC #endif
static id _instance;
// 覆寫 allocWithZone:,在此建立唯一實例(注意執行緒安全)
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
@synchronized(self) {
if (_instance == nil) {
_instance = [super allocWithZone:zone];
}
}
return _instance;
}
// 提供類方法供外界存取
+ (instancetype)sharedInstanceTool {
@synchronized(self) {
if (_instance == nil) {
_instance = [[self alloc] init];
}
}
return _instance;
}
// 避免回傳副本
- (id)copyWithZone:(struct _NSZone *)zone {
return _instance;
}
幾個細節值得說明:sharedInstanceTool 先檢查實例是否已存在,不存在才建立並回傳;之所以呼叫 super 而非 self,是因為 self 已經覆寫了基本的物件配置方法,底層記憶體配置得借父類之手完成。allocWithZone: 在 Cocoa 中負責配置記憶體並把引用計數設為 1,覆寫它是為了攔截重複配置;copyWithZone: 則是為了保證複製時仍回傳同一個實例。
+ (instancetype)sharedInstance {
static WMSingleton *singleton = nil;
if (!singleton) {
singleton = [[self alloc] initPrivate];
}
return singleton;
}
- (instancetype)init {
@throw [NSException exceptionWithName:@"這個是個單例"
reason:@"應該這樣調用 [WMSingleton sharedInstance]"
userInfo:nil];
}
// 真正的私有初始化
- (instancetype)initPrivate {
self = [super init];
return self;
}
這裡把 singleton 宣告為靜態變數。方法返回時靜態變數不會被釋放;初始值為 nil,第一次呼叫時建立物件並把位址寫入,之後無論呼叫多少次都指向同一個物件。由於這個變數是強引用且永不釋放,它指向的物件自然也永不釋放。而直接呼叫 init 會拋出例外,等於強制其他人走正確入口。
@synchronized 會產生互斥鎖以保證執行緒安全,但它有額外開銷。更現代的寫法是 dispatch_once:
static WMObject *_instance;
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [super allocWithZone:zone];
});
return _instance;
}
+ (instancetype)sharedInstance {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [[self alloc] init];
});
return _instance;
}
- (id)copyWithZone:(NSZone *)zone {
return _instance;
}
思路一致,差別只在用 dispatch_once_t 取代 @synchronized 來保證執行緒安全,效能更好也更簡潔。
// WMSingleton.h #define WMSingletonH(name) + (instancetype)shared##name;
// WMSingleton.m
#define WMSingletonM(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; \
}
使用方式:
// WMObject.h #import "WMSingleton.h" @interface WMObject : NSObject WMSingletonH(object) @end
// WMObject.m @implementation WMObject WMSingletonM(Car) @end
這樣一來,任何類只要兩行就能獲得執行緒安全的單例能力。