单例模式是指在内存中同时只能存在某个类的单个实例对象
class Cat:
def __init__(self, name, color):
self.name = name
self.color = color
obj = Cat('miao', 'white')
from moduleSettings import obj
def single_obj(cls):
obj = None
def wrapper(*args, **kwargs):
nonlocal obj # 改变作用域,使wrapper函数内的obj可以覆盖外层的obj
if not obj:
obj = cls(*args, **kwargs)
return obj
return wrapper
@single_obj
class Cat:
def __init__(self, name, color):
self.name = name
self.color = color
obj = Cat('miao', 'white')
obj2 = Cat('mm', 'black')
print(obj is obj2) # True
class Cat:
obj = None
def __init__(self, name, color):
self.name = name
self.color = color
@classmethod
def get_obj(cls, *args, **kwargs):
if not cls.obj:
cls.obj = cls(*args, **kwargs)
return cls.obj
obj = Cat.get_obj('miao', 'white')
obj2 = Cat.get_obj('mm', 'black')
print(obj is obj2) # True
class Cat:
obj = None
def __init__(self, name, color):
self.name = name
self.color = color
def __new__(cls, *args, **kwargs):
if not cls.obj:
cls.obj = super().__new__(cls)
return cls.obj
obj = Cat('miao', 'white')
obj2 = Cat('mm', 'black')
print(obj is obj2) # True
class MyType(type):
obj = None
def __call__(self, *args, **kwargs):
if not self.obj:
self.obj = super(MyType, self).__call__(*args, **kwargs) # 使用父类type的__call__方法
return self.obj
class Cat(metaclass=MyType):
def __init__(self, name, color):
self.name = name
self.color = color
obj = Cat('miao', 'white')
obj2 = Cat('mm', 'black')
print(obj is obj2) # True
class MyType(type):
obj = None
def __call__(self, *args, **kwargs):
if not self.obj:
self.obj = self.__new__(self) # 使用类的__new__方法生成一个空对象
self.__init__(self.obj, *args, **kwargs) # 不会生成新对象,但是可以更新对象的属性
return self.obj
class singleton(metaclass=MyType): # 所有需要实现单例模式的类,只需继承这个类即可
pass
class Cat(singleton):
def __init__(self, name, color):
self.name = name
self.color = color
obj = Cat('miao', 'white')
print(obj.__dict__) # {'name': 'miao', 'color': 'white'}
obj2 = Cat('mm', 'black')
print(obj2.__dict__) # {'name': 'mm', 'color': 'black'}
print(obj is obj2) # True
python中None对象就是一个单例模式的例子,即所有的None都是同一个对象。