The standalone mode and python implementation method are described in detail.
Singleton Mode
Singleton Pattern is a common software design Pattern designed to ensure that only one instance exists for a class. If you want to create only one instance for a class in the system, the single-instance object can be used.
For example, the configuration information of a server program is stored in a file, and the client reads the configuration file information through an AppConfig class. If the content of the configuration file needs to be used in many places during the program running, that is, the AppConfig object instance needs to be created in many places, this results in multiple AppConfig instance objects in the system, which seriously wastes memory resources, especially when the configuration file contains a lot of content. In fact, for classes like AppConfig, we hope that only one instance object exists during the program running.
Python Singleton Mode
Module implementation
The Python module is a natural Singleton mode, because the module is generated during the first import. the pyc file is directly loaded when the second import is performed. pyc file, instead of executing module code again. Therefore, we only need to define the relevant functions and data in a module to obtain a singleton object.
Mysingleton. py
class Singleton: def foo(self): print('foo')singleton=Singleton()
Other files
from mysingleton import singletonsingleton.foo()
Decorator implementation
def singleton(cls): _instance = {} def wraper(*args, **kargs): if cls not in _instance: _instance[cls] = cls(*args, **kargs) return _instance[cls] return wraper@singletonclass A(object): def __init__(self, x=0): self.x = xa1 = A(2)a2 = A(3)
Finally, the instance generates an object and stores it in _ instance. The value of _ instance must be
Implementation Based on the _ new _ Method
When an object is instantiated, the _ new _ method of the class is first executed (when we do not write it, the object is called by default. _ new _), instantiate the object, and then execute the _ init _ method of the class to initialize the object. All of us can implement the singleton mode based on this.
class Singleton(): def __new__(cls, *args, **kwargs): if not hasattr(cls,'_instance'): cls._instance=object.__new__(cls) return cls._instanceclass A(Singleton): def __init__(self,x): self.x=xa=A('han')b=A('tao')print(a.x)print(b.x)
To ensure thread security, you need to add a lock internally.
import threadingclass Singleton(): lock=threading.Lock def __new__(cls, *args, **kwargs): if not hasattr(cls,'_instance'): with cls.lock: if not hasattr(cls, '_instance'): cls._instance=object.__new__(cls) return cls._instanceclass A(Singleton): def __init__(self,x): self.x=xa=A('han')b=A('tao')print(a.x)print(b.x)
Two important notes:
1. Except for the module list, the essence of other modes is to set intermediate variables to determine whether the class has been instance. There is a thread security problem in the access and modification of intermediate variables: When the multi-threaded mode is enabled, locks are required.
2. The _ new _ method cannot avoid triggering _ init _ (). The initial member variables will be overwritten. No other methods.
PS: Let's take a look at the four implementation methods of the Python Singleton mode.
#-*-Encoding = UTF-8-*-print '---------------------- method 1 --------------------------' # method 1, implement the _ new _ method # and bind a class instance to the class Variable _ instance. # If cls. _ if the value of instance is None, the class has not been instantiated. If the value of instance is None, the class is instantiated and # If cls. _ if the value of instance is not None, cls is returned directly. _ instance class Singleton (object): def _ new _ (cls, * args, ** kw): if not hasattr (cls, '_ instance '): orig = super (Singleton, cls) cls. _ instance = orig. _ new _ (cls, * args, ** kw) return cls. _ instance class MyClass (Singleton): a = 1 one = MyClass () two. a = 3 print one. a #3 # one and two are identical. id (), =, is can be used to detect print id (one) #29097904 print id (two) #29097904 print one = two # True print one is two # True print '------------------------ method 2 --------------------------' # Method 2: Share attributes. The so-called Singleton is all references (instances and objects) having the same status (attributes) and behavior (methods) # all instances of the same class naturally have the same behavior (methods ), # Only ensure that all instances of the same class have the same status (attributes) you can # the simplest and most direct way to all instance shared properties is _ dict _ property pointing to (reference) the same dictionary (dict) # See: http://code.activestate.com/recipes/66531/ class Borg (object): _ state = {} def _ new _ (cls, * args, ** kw): ob = super (Borg, cls ). _ new _ (cls, * args, ** kw) ob. _ dict _ = cls. _ state return ob class MyClass2 (Borg): a = 1 one = MyClass2 () two = MyClass2 () # one and two are two different objects, id, =, is comparison results show two. a = 3 print one. a #3 print id (one) #28873680 print id (two) #28873712 print one = two # False print one is two # False # But one and two have the same (same _ dict _ attribute). For details, see: print id (one. _ dict _) #30104000 print id (two. _ dict _) #30104000 print '---------------------- method 3 --------------------------' # method 3: Upgrade Method 1 (or advanced) # use advanced python usage of _ metaclass _ (Meta class) class Singleton2 (type): def _ init _ (cls, name, bases, dict ): super (Singleton2, cls ). _ init _ (name, bases, dict) cls. _ instance = None def _ call _ (cls, * args, ** kw): if cls. _ instance is None: cls. _ instance = super (Singleton2, cls ). _ call _ (* args, ** kw) return cls. _ instance class MyClass3 (object): _ metaclass _ = Singleton2 one = MyClass3 () two = MyClass3 () two. a = 3 print one. a #3 print id (one) #31495472 print id (two) #31495472 print one = two # True print one is two # True print '------------------------ Method 4 --------------------------' # Method 4: upgrade (advanced) of method 1, # Use decorator. # This is a more pythonic and elegant method. # The Singleton class itself does not know that it is a singleton, because his own code is not def singleton (cls, * args, ** kw) of a singleton instance: instances ={} def _ singleton (): if cls not in instances: instances [cls] = cls (* args, ** kw) return instances [cls] return _ singleton @ singleton class MyClass4 (object ): a = 1 def _ init _ (self, x = 0): self. x = x one = MyClass4 () two = MyClass4 () two. a = 3 print one. a #3 print id (one) #29660784 print id (two) #29660784 print one = two # True print one is two # True one. x = 1 print one. x #1 print two. x #1
Summary
The above is a detailed explanation of how python achieves the single-profit mode. I hope it will help you. If you have any questions, please leave a message and I will reply to you in a timely manner. Thank you very much for your support for the help House website!