python学习笔记——单例模式的实现
单例模式是指在内存中同时只能存在某个类的单个实例对象
模块实现
- 在另一个模块中实现类并构造一个实例对象
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
__new__方法
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都是同一个对象。