1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| 3. 使用元类实现单例 元类控制类的创建过程。通过重写元类的 __call__ 方法,我们可以确保类只实例化一次。
class SingletonMeta(type): _instances = {}
def __call__(cls, *args, **kwargs): if cls not in cls._instances: instance = super().__call__(*args, **kwargs) cls._instances[cls] = instance return cls._instances[cls]
class Singleton(metaclass=SingletonMeta): def __init__(self): self.value = 42
# 测试 singleton1 = Singleton() singleton2 = Singleton()
print(singleton1 is singleton2) # 输出 True,表明两个对象是同一个实例
|