相比OC,Swift有很優雅的實現單例的寫法。
實現
單例類Tools
class Tools {
// 單例
static let shared = Tools()
// 私有化構造方法,不允許外界創建實例
private init() {
// 進行初始化工作
}
}
客戶端調用:
let tools = Tools.shared
說明
- 當嘗試使用
let tools = Tools()
這種方法去創建一個Tools
實例時,編譯器將會報錯,因為我們把init()
方法私有化了,類外無法通過構造方法創建新實例。
-
static let shared = Tools()
是線程安全的,并且將在第一次調用時進行賦值。這在蘋果的官方博客已有說明:
“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.”
“全局變量(還有結構體和枚舉體的靜態成員)的Lazy初始化方法會在其被訪問的時候調用一次。類似于調用dispatch_once
以保證其初始化的原子性。這樣就有了一種很酷的單次調用
方式:只聲明一個全局變量和私有的初始化方法即可。”
就這么愉快地寫好了單例。