__call__ 控制實例化Singleton 確保類全程序僅有一個實例。Python 透過元類(metaclass)攔截 __call__(即 Class() 呼叫)實現最純粹的單例,無需修改業務類、無需基類繼承、執行緒安全(需額外鎖)。
class Singleton(type):
def __call__(cls, *args, **kwargs):
print("Singleton call")
if not hasattr(cls, 'instance'):
cls.instance = super(Singleton, cls).__call__(*args, **kwargs)
return cls.instance
def __new__(cls, name, bases, dct):
print("Singleton new")
return type.__new__(cls, name, bases, dct)
def __init__(cls, name, bases, dct):
print("Singleton init")
super(Singleton, cls).__init__(name, bases, dct)
class Cache(object):
__metaclass__ = Singleton # Python 2 語法;Py3 用 class Cache(metaclass=Singleton):
def __new__(cls, *args, **kwargs):
print("Cache new")
return object.__new__(cls, *args, **kwargs)
def __init__(self, *args, **kwargs):
print("Cache init")
def __call__(self, *args, **kwargs):
print("Cache call")
print(Cache())
print(Cache())
# 輸出:
Singleton new
Singleton init
Singleton call
Cache new
Cache init
<__main__.Cache object at 0x...>
Singleton call
<__main__.Cache object at 0x...> # 同一物件
__new__:建立類物件(元類層面),僅在類定義時執行一次。__init__:初始化類物件,亦僅一次。__call__:每次 Cache() 呼叫都會觸發,攔截實例化邏輯。Cache 完全不知情,符合開閉原則。
class Cache(metaclass=Singleton):
...
import threading
class Singleton(type):
_instances = {}
_lock = threading.Lock()
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
with cls._lock:
if cls not in cls._instances:
cls._instances[cls] = super().__call__(*args, **kwargs)
return cls._instances[cls]
| 方法 | 優點 | 缺點 |
|---|---|---|
| 模組級變數 | 最簡單、Pythonic | 非類介面、難以延遲初始化 |
| 裝飾器 | 非侵入、可參數化 | 返回函式非類、isinstance 失效 |
基類 __new__ | 繼承即得 | 需繼承、多重繼承易衝突 |
元類 __call__ | 透明、支援繼承、可攔截建構參數 | 稍難理解、元類衝突需注意 |