Python 实现单例模式

# 使用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)

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/109e6e00b21a8ef55151d5f888f49427.html