上一節談過用 GCD 的 dispatch_once 快速實作單例。既然一個專案裡常有好幾個類都需要單例,為了更有效率地編碼,可以利用 C 語言的宏定義來一鍵生成。做法是先建立一個 Singleton.h 頭檔。
// 對應 @interface
#define singleton_interface(className) \
+ (className *)shared##className;
// 對應 @implementation
#define singleton_implementation(className) \
static className *_instance; \
+ (id)allocWithZone:(NSZone *)zone \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instance = [super allocWithZone:zone]; \
}); \
return _instance; \
} \
+ (className *)shared##className \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instance = [[self alloc] init]; \
}); \
return _instance; \
}這裡假設單例的取得方法名為 shared"ClassName"。由於 shared 與 "ClassName" 是連在一起的字串,要讓宏正確替換簽名中的 ClassName,前面得加上 ## 做拼接。此外,當宏定義超過一行時,需在每行結尾加上反斜線「\」表示續行;最後一行則不需要加。
下面說明如何在程式碼中呼叫。先看類的宣告:
#import "Singleton.h" @interface SoundTool : NSObject // 公開取得單例物件的方法 singleton_interface(SoundTool) @end
再看類的實作。若初始化時需要額外處理,可在 init 方法中完成:
@implementation SoundTool
singleton_implementation(SoundTool)
- (id)init {
// 初始化時的額外設定
}
@end如此一來,只要一行 singleton_implementation,就能為任意類快速套上執行緒安全的單例,大幅減少重複的樣板程式。