1 #Singleton mode: Unable to support multithreaded scenarios2 """3 class Singleton (object):4 def __init__ (self):5 Import Time6 time.sleep (1)7 @classmethod8 def instance (CLS, *args, **kwargs):9 if not hasattr (Singleton, "_instance"):Ten singleton._instance = Singleton (*args, **kwargs) One return singleton._instance A Import Threading - - def task (ARG): the obj = singleton.instance () - print (obj) - - For I in Range (Ten): + t = Threading. Thread (Target=task,args=[i,]) - T.start ()
First Kind
1 Import Time2 ImportThreading3 classSingleton (object):4_instance_lock =Threading. Lock ()5 def __init__(self):6Time.sleep (4)7 @classmethod8 defInstance (CLS, *args, * *Kwargs):9 if notHasattr (Singleton,"_instance"):Ten With Singleton._instance_lock: One if notHasattr (Singleton,"_instance"): ASingleton._instance = Singleton (*args, * *Kwargs) - returnsingleton._instance - defTask (ARG): theobj =singleton.instance () - Print(obj) - forIinchRange (10): -t = Threading. Thread (target=task,args=[I,]) + T.start () -obj =singleton.instance () + Print(obj)
The second Kind
1 Import Time2 ImportThreading3 classSingleton (object):4_instance_lock =Threading. Lock ()5 def __init__(self):6 Pass7 def __new__(CLS, *args, * *Kwargs):8 if notHasattr (Singleton,"_instance"):9 With Singleton._instance_lock:Ten if notHasattr (Singleton,"_instance"): OneSingleton._instance = object.__new__(CLS, *args, * *Kwargs) A returnsingleton._instance -Obj1 =Singleton () -Obj2 =Singleton () the Print(OBJ1,OBJ2)
Third Kind
1 ImportThreading2 classSingletontype (type):3_instance_lock =Threading. Lock ()4 def __call__(CLS, *args, * *Kwargs):5 if notHasattr (CLS,"_instance"):6 With Singletontype._instance_lock:7 if notHasattr (CLS,"_instance"):8Cls._instance = Super (SINGLETONTYPE,CLS).__call__(*args, * *Kwargs)9 returncls._instanceTen classFoo (metaclass=singletontype): One def __init__(self,name): ASelf.name =name -Obj1 = Foo ('name') -Obj2 = Foo ('name') the Print(OBJ1,OBJ2)Fourth Type
Four-in-one singleton mode in Python