Standalone mode and python implementation method, standalone python implementation
Singleton Mode
Singleton Pattern)Is a commonly used software design model, the main purpose of this model is to ensureA class only has one instance.. 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 Implementation of Singleton mode using modules
The Python module is the natural Singleton mode.Because the module will generate.pyc
File. When the second import is performed, the file is directly loaded..pyc
File, instead of executing the 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 we instantiate an object, yesFirst, the _ new _ method of the class is executed.(When we do not write data, object. _ new _ is called by default __),Instantiate object; ThenExecute the _ init _ method of the class.To initialize this 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.