單例模式屬于創(chuàng)建型的設(shè)計模式。它提供了一種創(chuàng)建對象的最佳方式。
示例代碼:
class MyClass {
static let shared = MyClass()
private init() {
// Private initialization to ensure just one instance is created.
}
}
使用方式:
let instance = MyClass.shared
// iOS 開發(fā)中常用的單例
UIApplication.shared
NSNotification.shared
NSUserDefaults.shared
理解
Swift的單行單例要怎么理解?從The Swift Programming Language(中文版)和Apple Swift Blog中可以找到答案。
Swift的語法中說明,使用關(guān)鍵字 static 來定義類型屬性。
存儲型類型屬性是延遲初始化的,它們只有在第一次被訪問的時候才會被初始化。即使它們被多個線程同時訪問,系統(tǒng)也保證只會對其進行一次初始化,并且不需要對其使用 lazy 修飾符?!?From The Swift Programming Language(中文版)
因此,使用static修飾的類型屬性,其自帶隱性的lazy修飾,且明確說明了即使它們被多個線程同時訪問,系統(tǒng)也只進行一次初始化。
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 use dispatch_once in your code: just declare a global variable with an initializer and mark it private. —— From Apple Swift Blog
這是Apple針對早期Swift版本的博客說明,這也說明了類型屬性的懶加載模式和初始化的原子性。而初始化的原子性又是單例模式必須遵從的原則。
除此以外,單例模式還需遵從「構(gòu)造函數(shù)必須是私有的」的這一原則,目的是為了防止使用構(gòu)造函數(shù)重復(fù)初始化多個實例。因此,少了private的構(gòu)造函數(shù)是不完整的單例模式!