The singleton pattern (Singleton pattern) is a commonly used software design pattern that is primarily intended to ensure that only one instance of a class exists.
A singleton can come in handy when you want the entire system to have only one instance of a class.
For example, the configuration information for a server program is stored in a file, and the client reads the configuration file information through a AppConfig class.
If there are many places where you need to use the contents of a configuration file during a program run, you need to create an instance of the AppConfig object in many places.
This results in the existence of multiple AppConfig instance objects in the system, which can be a serious waste of memory resources, especially in the case of many configuration file contents.
In fact, a class like AppConfig, we want only one instance object to exist during the run of the program.
In Python, we can implement a singleton pattern in a variety of ways:
- Using modules
- Use
__new__
- Using adorners (decorator)
- Using meta-classes (Metaclass)
1. Using __new__
In order for a class to appear only one instance, we can use it __new__ to control the creation of the instance, with the following code:
class Singleton (object): = None def__new__(CLS, *args, * *kw) :if not Cls._instance: = Super (Singleton, CLS). __new__ (CLS, *args, * *kw ) return cls._instance class MyClass (Singleton): = 1
In the above code, we associate an instance of the class with a class variable _instance , and if cls._instance None is created, the instance is returned directly cls._instance .
Implementation is as follows:
>>> one = MyClass ()>>> MyClass ()>>> one = = Twotrueis twotrue>>> ID (one), id (4303862608, 4303862608)
2. Using the module
In fact, thePython module is a natural singleton mode , because when the module is first imported, the file is generated .pyc , and when the second import, the file is loaded directly .pyc without executing the module code again.
Therefore, we just need to define the relevant functions and data in a module, we can get a singleton object. If we really want a singleton class, consider doing this:
class My_singleton (object): def foo (self): Pass = My_singleton ()
Save the above code in a file mysingleton.py , and then use:
from Import My_singleton My_singleton.foo ()
python--Single-Case mode