单例模式
什么是单例模式
单例模式,是一种常用的软件设计模式。在它的核心结构中只包含一个被称为单例的特殊类。通过单例模式可以保证系统中,应用该模式的类一个类只有一个实例。即一个类只有一个对象实例。
Python常用的单例模式写法
第一种(利用自定义类方法实现):
1 import threading 2 class Singleton(object): 3 instance_lock=threading.Lock() 4 def __init__(self,*args,**kwargs): 5 pass 6 @classmethod 7 def instance(cls,*args,**kwargs): 8 if not hasattr(cls,"_instance"): 9 with cls.instance_lock: 10 if not hasattr(Singleton,"_instance"): 11 cls._instance=Singleton(*args,**kwargs) 12 return cls._instance 13 14 def task(arg): 15 obj = Singleton.instance() 16 print(arg,obj) 17 for i in range(10): 18 t = threading.Thread(target=task,args=[i,]) 19 t.start()
第二种(利用__new__方法来实现):
1 import threading 2 class Singleton(object): 3 instance_lock=threading.Lock() 4 def __new__(cls, *args, **kwargs): 5 if not hasattr(cls,"_instance"): 6 with cls.instance_lock: 7 if not hasattr(cls,"_instance"): 8 cls._instance=object.__new__(cls,*args,**kwargs) 9 return cls._instance 10 11 obj1=Singleton() 12 obj2=Singleton() 13 print(obj1,obj2)
第三种(利用mataclass来实现):
1 import threading 2 class SingletonType(type): 3 instance=threading.Lock() 4 def __call__(cls, *args, **kwargs): 5 if not hasattr(cls,"_instance"): 6 if not hasattr(cls,"_instance"): 7 cls._instance=super(SingletonType,cls).__call__(*args,**kwargs) 8 return cls._instance 9 10 class Foo(metaclass=SingletonType): 11 def __init__(self): 12 pass 13 14 obj1=Foo() 15 obj2=Foo() 16 print(obj1,obj2)