Design pattern學習 – 3 (Singleton單例模式)

目的:

保證一個類別只會產生一個物件,而且要提供存取該物件的統一方法

須考慮的情境:

  • lazy initialization
  • Multithread

Swift sample:

// lazy Singleton: create the singleton object when needed
// Note: Global constants and variables are always computed lazily
// ref: https://docs.swift.org/swift-book/LanguageGuide/Properties.html#ID263
class SingletonGreed {
static let shared = SingletonGreed()
private init() {}
}
class SingletonThreadSafe {
private static var shared: SingletonThreadSafe?
private init() {}
static func getInstance() -> SingletonThreadSafe {
if shared == nil {
synced(self) {
if shared == nil {
shared = SingletonThreadSafe()
}
}
}
return shared!
}
static func synced(_ lock: Any, closure: () -> ()) {
objc_sync_enter(lock)
closure()
objc_sync_exit(lock)
}
}
view raw Singleton.swift hosted with ❤ by GitHub

Java sample:

%d 位部落客按了讚: