单例模式:保证一个类只有一个实例,并提供一个访问它的全局访问点。
单例大家应该都知道,这里更多来看一下,python实现单例的一些特性
装饰器来实现的版本
from functools import wraps
def singleton(cls):
_instance = {}
@wraps(cls)
def wrapper():
if cls not in _instance:
_instance[cls] = cls()
return wrapper
@singleton
class Child:
def __init__(self):
print("This is the singleton test")
def play(self):
print("Please be a happy kid")
if __name__ == "__main__":
t1 = Child()
t2 = Child()
if t1 is t2:
print("They are the same kid")
重写类的__new__方法
class Singleton(type):
_instance = None
def __new__(cls, *args, **kwargs):
if not hasattr(cls, '_instance'):
cls._instance = type.__new__(cls, *args, **kwargs)
return cls._instance
if __name__ == "__main__":
t1 = Singleton()
t2 = Singleton()
if t1 is t2:
print("They are the same thing")
高端版:元类实现。
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
class Child(metaclass=Singleton):
def __init__(self):
print("This is the singleton test")
def play(self):
print("Please be a happy kid")
if __name__ == "__main__":
t1 = Child()
t2 = Child()
if t1 is t2:
print("They are the same kid")