Python singleton pattern instance analysis
- 2020-04-02 14:29:07
- OfStack
This article illustrates the use of the Python singleton pattern. Share with you for your reference. The details are as follows:
Methods a
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
Disable the method with s/s. The object cannot be created directly.
2. Arbitration, privatization of singletons.
3.@staticmethod, staticmethod, called directly by class name.
4. S/s lock, code lock.
5. Inherit the object class, create the singleton by calling the object's s/s method, and then call the object s/s method s/s fully initialized.
6. Double check and lock, not only can achieve thread safety, but also make the performance is not greatly affected.
Method 2: use the decorator
#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 safety should also be added
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
I hope this article has helped you with your Python programming.