单例模式
程序运行期间此类只有一个实例存在,可以通过__new__创建实例时来做限制
1 class Singleton(object): 2 def __new__(cls, *args, **kwargs): 3 #如果使用__new__创建类实例时,类中没有instance属性,则认为此类还没有创建过实例, 4 #通过调用父类的__new__方法,super(Singleton, cls).__new__(cls)来创建实例 5 #super(Singleton, cls).__new__(cls)等价于object.__new__(cls) 6 #并把创建的实例,赋值给类属性instance 7 #下次在创建实例时,发现类中包含类属性instance,则直接返回类属性instance 8 #类属性instance的值为上次创建的实例 9 if not hasattr(cls,"instance"): 10 cls.instance = super(Singleton, cls).__new__(cls) 11 return cls.instance 12 13 s1 = Singleton() 14 s2 = Singleton() 15 print(s1 is s2) 16 #True
用装饰器的方式实现单例模式
1 def single(cls,*args,**kwargs): 2 instance = {} 3 def wrapper(*args,**kwargs): 4 if cls not in instance: 5 instance[cls] = cls(*args,**kwargs) 6 return instance[cls] 7 return wrapper 8 @single 9 class Foo: 10 def __init__(self,x,y): 11 self.x = x 12 self.y = y 13 14 f1 = Foo(1,2) 15 f2 = Foo(3.4) 16 print(f1.x,f1.y) 17 #正常显示1,2 18 print(f2.x,f2.y) 19 #还是1,2 20 #由于单例模式,第二个实例并未创建成功,在进入__new__时被截胡,所有f2还是f1 21 print(f1 is f2)