1 2 1 使用__new__方法 3 Python 4 class Singleton(object): def __new__(cls, *args, **kw): if not hasattr(cls, '_instance'): orig = super(Singleton, cls) cls._instance = orig.__new__(cls, *args, **kw) return cls._instanceclass MyClass(Singleton): a = 1 5 6 7 8 9 10 class Singleton(object): 11 def __new__(cls, *args, **kw): 12 if not hasattr(cls, '_instance'): 13 orig = super(Singleton, cls) 14 cls._instance = orig.__new__(cls, *args, **kw) 15 return cls._instance 16 17 class MyClass(Singleton): 18 a = 1 19 2 共享属性 20 创建实例时把所有实例的__dict__指向同一个字典,这样它们具有相同的属性和方法. 21 22 Python 23 class Borg(object): _state = {} def __new__(cls, *args, **kw): ob = super(Borg, cls).__new__(cls, *args, **kw) ob.__dict__ = cls._state return obclass MyClass2(Borg): a = 1 24 25 26 27 28 29 30 class Borg(object): 31 _state = {} 32 def __new__(cls, *args, **kw): 33 ob = super(Borg, cls).__new__(cls, *args, **kw) 34 ob.__dict__ = cls._state 35 return ob 36 37 class MyClass2(Borg): 38 a = 1 39 3 装饰器版本 40 Python 41 def singleton(cls, *args, **kw): instances = {} def getinstance(): if cls not in instances: instances[cls] = cls(*args, **kw) return instances[cls] return getinstance@singletonclass MyClass: ... 42 43 44 45 46 47 48 def singleton(cls, *args, **kw): 49 instances = {} 50 def getinstance(): 51 if cls not in instances: 52 instances[cls] = cls(*args, **kw) 53 return instances[cls] 54 return getinstance 55 56 @singleton 57 class MyClass: 58 ... 59 4 import方法 60 作为python的模块是天然的单例模式 61 62 Python 63 # mysingleton.pyclass My_Singleton(object): def foo(self): passmy_singleton = My_Singleton()# to usefrom mysingleton import my_singletonmy_singleton.foo() 64 65 66 67 # mysingleton.py 68 class My_Singleton(object): 69 def foo(self): 70 pass 71 72 my_singleton = My_Singleton() 73 74 # to use 75 from mysingleton import my_singleton 76 77 my_singleton.foo()