目的:
保證一個類別只會產生一個物件,而且要提供存取該物件的統一方法
須考慮的情境:
- lazy initialization
- Multithread
Swift sample:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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) | |
} | |
} |
Java sample: