Python单例模式
1 使用__new__方法
1 class Singleton(object): 2 def __new__(cls, *args, **kw): 3 if not hasattr(cls, '_instance'): 4 orig = super(Singleton, cls) 5 cls._instance = orig.__new__(cls, *args, **kw) 6 return cls._instance 7 8 class MyClass(Singleton): 9 a = 1
2 共享属性
创建实例时把所有实例的__dict__指向同一个字典,这样它们具有相同的属性和方法.
1 class Borg(object): 2 _state = {} 3 def __new__(cls, *args, **kw): 4 ob = super(Borg, cls).__new__(cls, *args, **kw) 5 ob.__dict__ = cls._state 6 return ob 7 8 class MyClass2(Borg): 9 a = 1
3 装饰器版本
1 def singleton(cls, *args, **kw): 2 instances = {} 3 def getinstance(): 4 if cls not in instances: 5 instances[cls] = cls(*args, **kw) 6 return instances[cls] 7 return getinstance 8 9 @singleton 10 class MyClass: 11 ...
卡卡,你好吗