單例是開發中最常使用的設計模式之一。它的目標很明確:在整個程式生命週期內,某個類別只有一個實例,而且只要 App 沒被終止,這個實例就不會被釋放。下面從「為什麼需要」講到「怎麼寫才正確」。
場景一:全域狀態的统一入口。很多時候整個系統只需要一個全域物件,這有助於協調整體行為。例如 App 中任何地方都可能需要使用者資訊,我們可以在登入時把資料寫入檔案,再由一個單例物件統一讀取,其他物件都透過它取得設定——這大幅簡化了複雜環境下的設定管理。
場景二:本質上只能有一個的資源管理者。比如你寫了一個播放音樂的類別,任何時刻都只該有一個實例在播放聲音。再比如一台電腦可以連接多台印表機,但上面的列印服務只能有一個,用單例就能避免兩個列印任務同時搶同一台印表機。
static id _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;
}
- (id)mutableCopyWithZone:(NSZone *)zone {
return _instance;
}static id _instance;
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
@synchronized(self) {
if (_instance == nil) {
_instance = [super allocWithZone:zone];
}
}
return _instance;
}
+ (instancetype)sharedInstance {
@synchronized(self) {
if (_instance == nil) {
_instance = [[self alloc] init];
}
}
return _instance;
}
- (id)copyWithZone:(NSZone *)zone {
return _instance;
}兩種寫法都能保證:無論使用者是透過 sharedInstance、alloc 還是 copy 取得實例,拿到的都是同一個物件。關鍵在於覆寫 allocWithZone:,把所有可能的建立路徑都堵起來。
如果既不用 dispatch_once 也不加鎖,寫法會變成這樣:
+ (instancetype)sharedInstance {
if (_instance == nil) {
_instance = [[self alloc] init];
}
}單執行緒下沒問題,但多執行緒就會出事。假設有 Thread 1 與 Thread 2 同時呼叫這個方法:
if (_instance == nil),判定成立,開始配置物件。_instance 赋值完成,它看到的仍然是 nil,判斷同樣成立。結果就是產生了兩個實例,單例的前提被破壞。
dispatch_once 保證傳入的 block 在整個程式執行過程中只會被執行一次。Thread 1 先進入並完成配置後,Thread 2 再呼叫時會直接被跳過,不會重複建立。
@synchronized 會把大括號內的程式碼視為一個需要加鎖的臨界區。Thread 1 進入後鎖定,Thread 2 若同時想執行就會進入睡眠;等 Thread 1 完成並釋放鎖,Thread 2 才被喚醒,此時 _instance 已不為 nil,判斷不成立,不會重複建立。
不過互斥鎖有明確的效能成本(鎖競爭與執行緒排程),所以實務上首選仍是 GCD 版本。
如果一個專案裡有多個類別都需要單例,每次都貼一次上面那幾十行實在太繁瑣。用宏包起來之後,每個類別只要一行就能搞定。
#define SingletonH(name) + (instancetype)shared##name;
#define SingletonM(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; \
} \
\
- (id)mutableCopyWithZone:(NSZone *)zone { \
return _instance; \
}這裡用到了 ## 這個 token 串接運算子,讓方法名稱能依類別自動變化,因此同一份宏可以用在任何類別上。
假設要在 ViewController 中使用:
// ViewController.h
#import <UIKit/UIKit.h>
#import "Singleton.h"
@interface ViewController : UIViewController
SingletonH(viewController)
@end
// ViewController.m
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
SingletonM(ViewController)
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"%@ %@ %@ %@",
[ViewController sharedViewController],
[ViewController sharedViewController],
[[ViewController alloc] init],
[[ViewController alloc] init]);
}
@end<ViewController: 0x7f897061bc00> <ViewController: 0x7f897061bc00> <ViewController: 0x7f897061bc00> <ViewController: 0x7f897061bc00>
四個物件的内存位址完全相同,證明不論走哪條路徑取得的都是同一個實例。
單例不是萬用解。它本質上是一個隱性的全域變數,會讓依賴關係變得不明顯、單元測試難以隔離。使用前先問自己:這個狀態真的必須全域唯一嗎?如果只是為了方便而處處使用單例,專案后期會很難拆。
注意職責邊界。例如網路層、快取層做成單例是合理的;但把「使用者資料」這種有明確生命週期的東西放進永久單例,登出時忘記清理就會釀成資料外洩。
本文整理自「西木柚子」於簡書發佈的相關文章。