# <单例> # Singleton # # 单例:即单个实例,指的是同一个类实例化多次的结果指向同一个对象,用于节省内存空间 # 如果我们从配置文件中读取配置来进行实例化,在配置相同的情况下,就没必要重复产生对象浪费内存了 # # 实现原理,为了节省空间,结合需求让同一个类多次实例化后结果指向同一个对象 # 可理解为开关,一次进入后更改 instance的状态 +_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+ << 1.类方法实现 >> class Singleton: __instance = None def change_instance(cls): if not cls.__instance: cls.__instance = cls() return cls.__instance +_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+ << 2.装饰器实现 >> def outer(fn): _instance = None def inner(*args, **kwargs): nonlocal _instance if _instance == None: _instance = fn(*args, **kwargs) return _instance return inner @outer class Music: pass +_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+ << 3.元类方法实现 >> class SingleMeta(type): __instance = None def __call__(cls, *args, **kwargs): if SingleMeta.__instance == None: SingleMeta.__instance = object.__new__(cls) # {} cls.__init__(SingleMeta.__instance, *args, **kwargs) print(SingleMeta.__instance.__dict__) # {} {‘name‘: ‘egon‘} return SingleMeta.__instance class Songs(metaclass=SingleMeta): def __init__(self): self.name = ‘egon‘ pass +_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+ << 4.反射方法实现 >> class Singleton(object): def __new__(cls): if not hasattr(cls, ‘instance‘): cls.instance = super().__new__(cls) return cls.instance +_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+
原文地址:https://www.cnblogs.com/max404/p/10808298.html
时间: 2024-10-17 14:28:51