Python Singleton mode and Python Mode
Method 1
Python code
- Import threading
- Class Singleton (object ):
- _ Instance = None
- _ Lock = threading. Lock () # used to synchronize code
- Def _ init _ (self ):
- "Disable the _ init _ method"
-
- @ Staticmethod
- Def getInstance ():
- If not Singleton. _ instance:
- Singleton. _ lock. acquire ()
- If not Singleton. _ instance:
- Singleton. _ instance = object. _ new _ (Singleton)
- Object. _ init _ (Singleton. _ instance)
- Singleton. _ lock. release ()
- Return Singleton. _ instance
1. Disable the _ init _ method. You cannot directly create an object.
2. _ instance: the singleton object is private.
3. @ staticmethod: static method, called directly by class name.
4. _ lock: code lock.
5. inherit from the object class, create a singleton object by calling the _ new _ method of the object, and call the complete initialization of the _ init _ method of the object.
6. Double check and locking can not only achieve thread security, but also ensure high performance.
Method 2: decorator
Python code
- # Encoding = UTF-8
- Def singleton (cls ):
- Instances = {}
- Def getInstance ():
- If cls not in instances:
- Instances [cls] = cls ()
- Return instances [cls]
- Return getInstance
-
- @ Singleton
- Class SingletonClass:
- Pass
- If _ name _ = '_ main __':
- S = SingletonClass ()
- S2 = SingletonClass ()
- Print s
- Print s2
Thread security should also be added
Appendix: High Performance
Python code
- Import threading
- Class Sing (object ):
- Def _ init __():
- "Disable the _ init _ method"
- _ Inst = None # make it so-called private
- _ Lock = threading. Lock () # used to synchronize code
-
- @ Staticmethod
- Def getInst ():
- Sing. _ lock. acquire ()
- If not Sing. _ inst:
- Sing. _ inst = object. _ new _ (Sing)
- Object. _ init _ (Sing. _ inst)
- Sing. _ lock. release ()
- Return Sing. _ inst