Python使用装饰器(decorator)实现单例模式

#2.Python如何实现单例模式?其他23种设计模式python如何实现?
#第一 使用__metaclass__(元类)的高级python用法
#使用装饰器(decorator),
#这是一种更pythonic,更elegant的方法,
#单例类本身根本不知道自己是单例的,因为他本身(自己的代码)并不是单例的  # 使用装饰器(decorator),
# 这是一种更pythonic,更elegant的方法,
# 单例类本身根本不知道自己是单例的,因为他本身(自己的代码)并不是单例的
def singleton(cls, *args, **kw):
    instances = {}

    def _singleton():
        if cls not in instances:
            instances[cls] = cls(*args, **kw)
        return instances[cls]

    return _singleton


@singleton
class MyClass4(object):
    a = 1

    def __init__(self, x=0):
        self.x = x


one = MyClass4()
two = MyClass4()

two.a = 3
print (one.a)
print (id(one))
print (id(two))
print (one == two)
print (two.x)
one.x = 1
print (one.x)
print (one is two)
# 3
# 1541133085328
# 1541133085328
# True
# 0
# 1
# True
 

猜你喜欢

转载自blog.csdn.net/C_TestMG/article/details/85065365