Method One
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, and you cannot create objects directly.
2.__instance, privatization of single-instance objects.
[email protected], static method, directly called through the class name.
4.__lock, code lock.
5. Inherit the object class, create a singleton object by calling the __new__ method of object, and then call the __init__ method of object to complete the initialization.
6. Double check lock, both to achieve thread safety and performance is not greatly affected.
Method Two: Use 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
You should also add thread safety
Attached: Performance no method one high
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
Python single-instance mode