Python 实现单例模式

xuxingzhuang 2017-10-12

# 使用Python实现单例模式
 
# 方法一: 使用__new__方法
class SingleTon(object):
    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, '_instance'):
            cls._instance = object.__new__(cls, *args, **kwargs)
        return cls._instance
 
 
class TestClass(SingleTon):
    a = 1
 
 
# 方法二: 使用装饰器(decorator)
def SingleTon1(cls, *args, **kwargs):
    instances = {}
    def _singleTon():
        if cls not in instances:
            instances[cls] = cls(*args, **kwargs)
        return  instances[cls]
    return _singleTon
 
 
@SingleTon1
class TestClass1(object):
    a = 1
 
 
 
# 共享属性  属性是共享的,但是并非单例模式
class SingleTon3(object):
    _state = {}
    def __new__(cls, *args, **kwargs):
        obj = object.__new__(cls, *args, **kwargs)
        obj.__dict__ = cls._state
        return obj
 
 
class TestClass3(SingleTon3):
    a = 1
 
test1 = TestClass3()
test2 = TestClass3()
test1.a = 2
print(test1.a)
print(test2.a)
print(test1)
print(test2)

相关推荐