Python中单例模式总结
一、单例模式
a、单例模式分为四种:文件,类,基于__new__方法实现单例模式,基于metaclass方式实现
b、类实现如下:
classSigletion(objects): importtime def__init__(self): time.sleep(1) @classmethod definstance(cls,*args,**kwargs) ifnothasattr(Sigletion,'_instance'): Sigletion._instance=Sigletion(*args,**kwargs) returnSigletion._instance importthreading daftask(arg): obj=Sigletion.instance() print(obj) foriinrange(10): t=threading.Thread(target=task,args=[i,]) t.start()
c、基于__new__方法实现单例模式
importtime importthreading classSingleton(object): _instance_lock=threading.Lock() def__init__(self): pass def__new__(cls,*args,**kwargs): ifnothasattr(Singleton,"_instance"): withSingleton._instance_lock: ifnothasattr(Singleton,"_instance"): Singleton._instance=object.__new__(cls,*args,**kwargs) returnSingleton._instance obj1=Singleton() obj2=Singleton() print(obj1,obj2) deftask(arg): obj=Singleton() print(obj) foriinrange(10): t=threading.Thread(target=task,args=[i,]) t.start()
d、基于metaclass方式实现单例模式
"""
1.对象是类创建,创建对象时候类的__init__方法自动执行,对象()执行类的__call__方法
2.类是type创建,创建类时候type的__init__方法自动执行,类()执行type的__call__方法(类的__new__方法,类的__init__方法)
#第0步:执行type的__init__方法【类是type的对象】 classFoo: def__init__(self): pass def__call__(self,*args,**kwargs): pass #第1步:执行type的__call__方法 #1.1调用Foo类(是type的对象)的__new__方法,用于创建对象。 #1.2调用Foo类(是type的对象)的__init__方法,用于对对象初始化。 obj=Foo() #第2步:执行Foodef__call__方法 obj() """ importthreading classSingletonType(type): _instace_lock=threading.Lock() def__call__(cls,*args,**kwargs): ifnothasattr(cls,"_instance"): withSingletonType._instace_lock: ifnothasattr(cls,"_instance"): cls._instance=super(SingletonType,cls).__call__(*args,**kwargs) returncls._instance classFoo(metaclass=SingletonType): def__init__(self,name): self.name=name obj1=Foo('name') obj2=Foo('name') print(obj1,obj2)