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)
本文出自 “许大树” 博客,请务必保留此出处http://abelxu.blog.51cto.com/9909959/1967293
原文地址:http://abelxu.blog.51cto.com/9909959/1967293