1, what is the singleton:
Refers to a singleton pattern class has only one instance of the object, create an instance of the object, the instance is created and then a return object reference. (Simply say that two instances of objects same ID, these saving memory space)
2, Singleton pattern created:
For example create a class, such as the universe is only one Earth to help understand the singleton
class Earth: pass a=Earth() print(a) B = Earth () Print (B) ***** ****** Results 32096552 32096496 we can see two examples are not the same memory ID, the class is not a singleton
So how can let the class to create only one instance, and then create instances is to return the last reference to the object it?
We understand, python, a class object instance is created by calling the parent object of __new __ (cls) method to create an object
We can go to the implementation class by overriding __new __ (cls) method to create only one instance:
class Earth (Object): __instance = None DEF __new__ (CLS): IF CLS. __instance == None: # if __instance empty prove for the first time to create an instance . CLS __instance . = Object __new__ (CLS) return CLS. __instance the else : # If it is not the first time to create an instance, return to the previous object reference return . CLS __instance a = Earth () Print (the above mentioned id (a)) B = Earth () Print (B) ****** ***** Results 1730389200 1730389200
The above example we create a singleton class by __new__ method, but the singleton class and then use multithreading is there will be some problems. We need to add mutex way to solve the problem.
import threading class Earth(object): _instance_lock=threading.Lock() def __init__(self): pass def __new__(cls,*args,**kwargs): if not hasattr(Earth,'_instance'): with Earth._instance_lock: if not hasattr(Earth,'_instance'): Earth._instance=object.__new__(cls) return Earth._instance a=Earth() b=Earth() print(a,b) def task(arg): obj=Earth() print(obj) for i in range(10): t=threading.Thread(target=task,args=[i,]) t.start() *****result***** <__main__.Singleton object at 0x00000000029D06A0> <__main__.Singleton object at 0x00000000029D06A0> <__main__.Singleton object at 0x00000000029D06A0> <__main__.Singleton object at 0x00000000029D06A0> <__main__.Singleton object at 0x00000000029D06A0> <__main__.Singleton object at 0x00000000029D06A0> <__main__.Singleton object at 0x00000000029D06A0> <__main__.Singleton object at 0x00000000029D06A0> <__main__.Singleton object at 0x00000000029D06A0> <__main__.Singleton object at 0x00000000029D06A0>
3, other methods for creating the single Example: 3, the use of class 1, using the module, the decorator 4 2, based on the way metaclass
Specific reference blog: https://www.cnblogs.com/huchong/p/8244279.html