相比OC,Swift有很優(yōu)雅的實現(xiàn)單例的寫法。
實現(xiàn)
單例類Tools
class Tools {
// 單例
static let shared = Tools()
// 私有化構(gòu)造方法,不允許外界創(chuàng)建實例
private init() {
// 進行初始化工作
}
}
客戶端調(diào)用:
let tools = Tools.shared
說明
- 當嘗試使用
let tools = Tools()
這種方法去創(chuàng)建一個Tools
實例時,編譯器將會報錯,因為我們把init()
方法私有化了,類外無法通過構(gòu)造方法創(chuàng)建新實例。
-
static let shared = Tools()
是線程安全的,并且將在第一次調(diào)用時進行賦值。這在蘋果的官方博客已有說明:
“The lazy initializer for a global variable (also for static members of structs and enums) is run the first time that global is accessed, and is launched as
dispatch_once
to make sure that the initialization is atomic. This enables a cool way to usedispatch_once
in your code: just declare a global variable with an initializer and mark it private.”
“全局變量(還有結(jié)構(gòu)體和枚舉體的靜態(tài)成員)的Lazy初始化方法會在其被訪問的時候調(diào)用一次。類似于調(diào)用dispatch_once
以保證其初始化的原子性。這樣就有了一種很酷的單次調(diào)用
方式:只聲明一個全局變量和私有的初始化方法即可。”
就這么愉快地寫好了單例。