Singleton 保證一個 Class 只會有一個 Instance,並提供一個存取該 Instance 的全域節點。
Singleton 解決了兩個問題,但也因此違反了 Single Responsibility Principle。
Solution
所有的實現都包含以下兩個步驟:
- 將預設 constructor 設為 private,防止其他 object 使用 Singleton class 的
new operator
- 建立一個 static 建構方法作為 constructor。該函數會調用 private constructor 來建立物件,並將其儲存在一個靜態 field。之後所有對於該函數的調用都會回傳這一個 cache 物件。
如果程式碼能夠存取 Singleton class,那就用呼叫 Singleton 的靜態方法。無論何時調用該方法,都會回傳相同的物件。
Real-World Analogy
政府是 Singleton pattern 的一個很好的比喻。一個國家只有一個政府機關,不管組成政府的每個人的身份是什麼,該政府 X 是識別這些掌管者的全域存取節點。
Structure
Pseudocode
Applicability
適用於建立一個物件需要消耗的資源過多的時候,例如要存取 IO 和資料庫等資源
- 如果程式中的某個 class 對於所有 Client 只有一個可用的 Instance,可以使用 Singleton
- Singleton pattern 禁止透過除了特殊 constructor 方法以外的任何方式來建立自身 class 的物件。該方法可以建立一個新物件,但如果該物件已經被建立,則回傳已有的物件
- 如果需要更加嚴格的控制全域變數,可以使用 Singleton pattern
- Singleton pattern 跟全域變數不同,它只保證 class 存在一個 Instance。除了 Singleton class自己以外,無法透過其他方式替換 cache 的 Instance。
需要注意的是,隨時可以調整限制並設定生成 Singleton instance 的數量,只需要修改 獲得 instance 方法,亦即 getInstance 中的程式即可。
How to Implement
- 在 Class 中增加一個 private 靜態欄位來儲存 instance
- 宣告一個 public 靜態建立方法來獲得 singleton instance
- 在靜態方法中實現 "延遲初始化"。該方法會在首次被調用的時候建立一個新物件,並將其儲存在靜態欄位。之後該方法每次被調用都會回傳該 instance
- 將 class 的 constructor 設定為 private。Class 的靜態方法依舊能調用 constructor,但是其他物件不能
- 檢查 Client 程式碼,將對 singleton 的 constructor 的調用方式替換成其靜態建立方法
Pros and Cons
Pros
- 可以保證一個 class 只有一個 instance
- 得到一個指向該 Instance 的全域存取節點
- 只在首次請求 Singleton 物件的時候進行初始化
Cons
- 違反了 Single Responsibility Principle
- Singleton 可能會掩蓋不良的設計,比如程式元件彼此的關聯過多
- 該 pattern 在多執行緒情況下需要進行特別處理,避免多個執行緒多次建立 instance
- Singleton 的 Client 程式碼單元測試可能會比較困難。因為許多測試框架會用基於繼承的方式來建立模擬物件。由於 Singleton 的 constructor 是 private 的,而且絕大部分的語言無法重寫靜態方法,所以需要想出仔細考慮模擬 Singleton 的方法。或是就不要撰寫測試或不要使用 Singleton pattern
Relations with Other Patterns
Code Examples
Python
Naïve
class SingletonMeta(type):
"""
The Singleton class can be implemented in different ways in Python. Some
possible methods include: base class, decorator, metaclass. We will use the
metaclass because it is best suited for this purpose.
"""
_instances = {}
def __call__(cls, *args, **kwargs):
"""
Possible changes to the value of the `__init__` argument do not affect
the returned instance.
"""
if cls not in cls._instances:
instance = super().__call__(*args, **kwargs)
cls._instances[cls] = instance
return cls._instances[cls]
class Singleton(metaclass=SingletonMeta):
def some_business_logic(self):
"""
Finally, any singleton should define some business logic, which can be
executed on its instance.
"""
if __name__ == "__main__":
s1 = Singleton()
s2 = Singleton()
if id(s1) == id(s2):
print("Singleton works, both variables contain the same instance.")
else:
print("Singleton failed, variables contain different instances.")
Thread-safe
from threading import Lock, Thread
class SingletonMeta(type):
"""
This is a thread-safe implementation of Singleton.
"""
_instances = {}
_lock: Lock = Lock()
"""
We now have a lock object that will be used to synchronize threads during
first access to the Singleton.
"""
def __call__(cls, *args, **kwargs):
"""
Possible changes to the value of the `__init__` argument do not affect
the returned instance.
"""
with cls._lock:
if cls not in cls._instances:
instance = super().__call__(*args, **kwargs)
cls._instances[cls] = instance
return cls._instances[cls]
class Singleton(metaclass=SingletonMeta):
value: str = None
"""
We'll use this property to prove that our Singleton really works.
"""
def __init__(self, value: str) -> None:
self.value = value
def some_business_logic(self):
"""
Finally, any singleton should define some business logic, which can be
executed on its instance.
"""
def test_singleton(value: str) -> None:
singleton = Singleton(value)
print(singleton.value)
if __name__ == "__main__":
print("If you see the same value, then singleton was reused (yay!)\n"
"If you see different values, "
"then 2 singletons were created (booo!!)\n\n"
"RESULT:\n")
process1 = Thread(target=test_singleton, args=("FOO",))
process2 = Thread(target=test_singleton, args=("BAR",))
process1.start()
process2.start()
JavaScript
class Singleton {
private static instance: Singleton;
private constructor() { }
public static getInstance(): Singleton {
if (!Singleton.instance) {
Singleton.instance = new Singleton();
}
return Singleton.instance;
}
public someBusinessLogic() {
}
}
function clientCode() {
const s1 = Singleton.getInstance();
const s2 = Singleton.getInstance();
if (s1 === s2) {
console.log('Singleton works, both variables contain the same instance.');
} else {
console.log('Singleton failed, variables contain different instances.');
}
}
clientCode();
Go
package main
import (
"fmt"
"sync"
)
var lock = &sync.Mutex{}
type single struct {
}
var singleInstance *single
func getInstance() *single {
if singleInstance == nil {
lock.Lock()
defer lock.Unlock()
if singleInstance == nil {
fmt.Println("Creating single instance now.")
singleInstance = &single{}
} else {
fmt.Println("Single instance already created.")
}
} else {
fmt.Println("Single instance already created.")
}
return singleInstance
}
Swift
Conceptual
import XCTest
class Singleton {
static var shared: Singleton = {
let instance = Singleton()
return instance
}()
private init() {}
func someBusinessLogic() -> String {
return "Result of the 'someBusinessLogic' call"
}
}
extension Singleton: NSCopying {
func copy(with zone: NSZone? = nil) -> Any {
return self
}
}
class Client {
static func someClientCode() {
let instance1 = Singleton.shared
let instance2 = Singleton.shared
if (instance1 === instance2) {
print("Singleton works, both variables contain the same instance.")
} else {
print("Singleton failed, variables contain different instances.")
}
}
}
class SingletonConceptual: XCTestCase {
func testSingletonConceptual() {
Client.someClientCode()
}
}
Real World
import XCTest
class SingletonRealWorld: XCTestCase {
func testSingletonRealWorld() {
let listVC = MessagesListVC()
let chatVC = ChatVC()
listVC.startReceiveMessages()
chatVC.startReceiveMessages()
}
}
class BaseVC: UIViewController, MessageSubscriber {
func accept(new messages: [Message]) {
}
func accept(removed messages: [Message]) {
}
func startReceiveMessages() {
FriendsChatService.shared.add(subscriber: self)
}
}
class MessagesListVC: BaseVC {
override func accept(new messages: [Message]) {
print("MessagesListVC accepted 'new messages'")
}
override func accept(removed messages: [Message]) {
print("MessagesListVC accepted 'removed messages'")
}
override func startReceiveMessages() {
print("MessagesListVC starts receive messages")
super.startReceiveMessages()
}
}
class ChatVC: BaseVC {
override func accept(new messages: [Message]) {
print("ChatVC accepted 'new messages'")
}
override func accept(removed messages: [Message]) {
print("ChatVC accepted 'removed messages'")
}
override func startReceiveMessages() {
print("ChatVC starts receive messages")
super.startReceiveMessages()
}
}
protocol MessageSubscriber {
func accept(new messages: [Message])
func accept(removed messages: [Message])
}
protocol MessageService {
func add(subscriber: MessageSubscriber)
}
struct Message {
let id: Int
let text: String
}
class FriendsChatService: MessageService {
static let shared = FriendsChatService()
private var subscribers = [MessageSubscriber]()
func add(subscriber: MessageSubscriber) {
subscribers.append(subscriber)
startFetching()
}
func startFetching() {
let newMessages = [Message(id: 0, text: "Text0"),
Message(id: 5, text: "Text5"),
Message(id: 10, text: "Text10")]
let removedMessages = [Message(id: 1, text: "Text0")]
receivedNew(messages: newMessages)
receivedRemoved(messages: removedMessages)
}
}
private extension FriendsChatService {
func receivedNew(messages: [Message]) {
subscribers.forEach { item in
item.accept(new: messages)
}
}
func receivedRemoved(messages: [Message]) {
subscribers.forEach { item in
item.accept(removed: messages)
}
}
}
Reference
- https://refactoring.guru/design-patterns/singleton