"""
单例模式
1. 类方法实现
2. new方法实现
3. 元类方法实现(推荐)
"""
# 示例
class Test(object):
def __new__(cls, *args, **kwargs):
return "Hello World"
t = Test()
print(t) # Hello World
"""
1. 类方法实现
"""
class Test(object):
__instance = None
@classmethod
def instance(cls, id):
if cls.__instance:
return cls.__instance
else:
cls.__instance = cls(id)
return cls.__instance
def __init__(self, id):
self.id = id
t = Test.instance(1)
t = Test.instance(2)
t = Test.instance(3)
print(t.id) # 1 我们发现不是后面的3了,而是初始的1
"""
2. __new__() 方式的单例模式
这种单例会保持最后一次的值,原因如下:
__new__ 说明:在new方法中一旦我们return了一个值,那么new就会去主动的调用init方法
"""
class Test(object):
def __init__(self, id):
self.id = id
def __new__(cls, *args, **kwargs):
if not hasattr(cls, 'instance'):
cls.instance = super(Test, cls).__new__(cls)
return cls.instance # 主动调用init函数
t = Test(1)
t1 = Test(2)
print(t.id) # 2
print(t1.id) # 2
print(t is t1) # True
# 不过我们可以发现,我们每次初始化都会调用init,这样一来就只会是最后一次初始化的值
"""
3. 元类实现单例,推荐使用
前面我们学习了元类的 __new__ 可以用于创建类对象
而当一个类在实例化时,将会调用的的是元类的 __call__
"""
class Singleton(type):
# new用于创建类对象
def __new__(cls, class_name, class_parents, class_attr):
# 给类添加一个instance属性
class_attr['instance'] = None
# 返回类对象
return super(Singleton, cls).__new__(cls, class_name, class_parents, class_attr)
# 类对象实例化时将调用
def __call__(self, *args, **kwargs):
if self.instance is None:
self.instance = super(Singleton, self).__call__(*args, **kwargs)
return self.instance
class Test(metaclass=Singleton):
def __init__(self, id):
self.id = id
t = Test(1)
t1 = Test(2)
print(t.id) # 1
print(t1.id) # 1
print(t is t1) # True