標籤:ios singleton
自從設計模式出現以後,關於單例模式的爭執就一直存在。我們很多時候需要一個全域的東西,保證全域僅有一份即可,這個時候單例是最佳的選擇,但在多線程的環境下也需要做好線程保護。
在iOS下的UIApplication和NSFileManager就是很不錯的例子——我們總有時候需要用到單例模式。不過寫起代碼來還是值得推敲一下:
最簡單的例子如下,假設我們有一個testClass的類需要實現單例:
+ (id)sharedInstance { static testClass *sharedInstance = nil; if (!sharedInstance) { sharedInstance = [[self alloc] init]; } return sharedInstance;} 當然,你一眼就會發現,這雷根本沒有考慮安全執行緒的問題,讓我們加上線程鎖。
+ (id)sharedInstance { static testClass *sharedInstance = nil; @synchronized(self) { if (!sharedInstance) { sharedInstance = [[self alloc] init]; } } return sharedInstance;} 這是很常見的寫法,如果繼續下去,還需要重載retainCount,retain,等等方法,這個蘋果的官方文檔有論述到,甚至還有例子。
不過,在GCD推出後,有個dispatch_once的方法,可以是單例的實現更加容易,dispatch_once的函數原型如下:
void dispatch_once(dispatch_once_t *predicate, dispatch_block_t block);
我們可以看到這個函數接收一個dispatch_once_t的參數,還有一個塊參數。對於一個給定的predicate來說,該函數會保證相關的塊必定會執行,而且只執行一次,最重要的是——這個方法是完全安全執行緒的。需要注意的是,對於只需要執行一次的塊來說,傳入的predicate必須是完全相同的,所以predicate常常會用static或者global來修飾。
+ (id)sharedInstance { static testClass *sharedInstance = nil; static dispatch_once_t once; dispatch_once(&once, ^{ sharedInstance = [[self alloc] init]; }); return sharedInstance;}
這樣寫的好處很明顯:代碼簡單清晰,而且做到了安全執行緒。另外,dispatch_once很高效,沒有實現重量級的同步機制,這樣實現的效率也很高。