One, single case mode
Singleton mode is the simplest and most famous design pattern in the process of application development. Singleton mode provides a mechanism for a class that has only one specific type of object.
Typically used in scenarios such as logging, database operations, and so on, the program can only generate one instance at run time, avoiding conflicting access requests to the same resource.
Second, how to design a single case mode
(1) Overriding constructor __new__ method
Class Singleton (object): def __new__ (self): if isn't hasattr (self, ' instance '): self.instance = Super ( singleton,self). __new__ (self) return self.instance a = Singleton () b = Singleton () Print ID (a), ID (a)
The main idea of this method is to overlay the instantiation function __new__ (), in which the judgment is added to check whether the object exists. Hasattr is a special way for Python to see if an object has a property.
Of course, if you want to inherit this singleton, you must not forget to override the __new__ method in the subclass, otherwise you will overwrite the method that has been modified in the parent class.
Class Singleton (object): def __new__ (self): if isn't hasattr (self, ' instance '): self.instance = Super ( singleton,self). __new__ (self) return self.instance class Test (Singleton): def __new__ (self): Super (Singleton,self). __new__ (self) a = Test () b = Test () Print ID (a), ID (a)
(2) Meta-class programming rewrite __call__ method
A meta-class is a class that can redefine the behavior of a class by creating a meta-class. When we create a class with Class A, Python creates it with a = type (name, bases, Dict), where name is the name of the class, base is the base class, and Dict is an attribute variable.
The following is a discussion of the meta-class type construction class and the process of an instance:
Class Meta (Type): def __init__ (self, name, bases, attrs): print ' init ' super (Meta, self). __INIT__ (Name, Bases, Attrs) def __new__ (meta,name, Bases, attrs): print "new" return Super (Meta,meta). __new__ (Meta, Name, bases, Attrs) def __call__ (self): print "Call" return Super (meta,self). __call__ () s = ["Student ", (object,), {" Name ":" Joe "," Age ": +} ] classstudent = Meta (*s) instance = Classstudent ()
As you can see, the result is:
The process is to first __new__ create an instance of the class, as input to the __init__, to complete the function of the constructor. Of course, the result of this process is to obtain an instance and is called:
Student class, Classstudent is a reference to this class. When a () call is made, the callable instantiation of the instance of the meta is implemented.
At this point, we have a simple understanding of the function of the relevant magic function .
The method of implementing a singleton pattern through a meta-class is:
Class Meta (type): _instance = {} def __init__ (self, name, bases, attrs): print ' init ' super (Meta, self) . __init__ (name, bases, Attrs) def __new__ (meta,name, Bases, attrs): print "new" return Super (Meta,meta). _ _new__ (Meta,name, bases, Attrs) def __call__ (self): print ' call ' if self ' not ' in ' self._instance: Self . _instance[self] = Super (meta,self). __call__ () return self._instance[self] s = ["Student", (object,), {"Name ":" Joe "," age ": [+ ]] classstudent = Meta (*s) Instance1 = classstudent () Instance2 = Classstudent () Print ID ( INSTANCE1), ID (INSTANCE2)
At this point, we can see that through the meta-class programming to implement the Singleton mode, you need to change the __call__ function, because its constructor is to construct the class, rather than in the process of generating the instance, the method of generating the instance through the function call calls __call__, so it operates at this location.
Of course, the use of the Singleton class can be set in the class by the __metaclass__ property, instead of the method directly generated with the type class.
Class Meta (type): _instance = {} def __init__ (self, name, bases, attrs): print ' init ' super (Meta, self) . __init__ (name, bases, Attrs) def __new__ (meta,name, Bases, attrs): print "new" return Super (Meta,meta). _ _new__ (Meta,name, bases, Attrs) def __call__ (self): print ' call ' if self ' not ' in ' self._instance: Self . _instance[self] = Super (meta,self). __call__ () return self._instance[self] class Classstudent (object): __ metaclass__ = Meta pass Instance1 = classstudent () Instance2 = Classstudent () Print ID (INSTANCE1), ID ( INSTANCE2)
When a user defines a class, the Python interpreter looks for the "__metaclass__" attribute in the current class and, if found, creates the class from the code corresponding to the property, and if it is not found, continues to find the parent class with the same rule. If "__metaclass__" is not found in any of the parent classes, the built-in type is used to create the class object.
Of course, for Python3, a new method for declaring a singleton is added:
Class Test (Metaclass = Mymeta): Pass
Three, Monostate mode
For the above singleton pattern, the focus is on generating a single instance, and the programmer usually needs to share the same state with the instance, so sometimes it needs to focus on state and behavior rather than identity. This concept is monostate (single State) mode. Python's process for implementing this pattern is easier:
Class Classstudent (object): _age = pass Instance1 = classstudent () Instance2 = Classstudent () Print ID ( INSTANCE1), id (instance2) print Instance1._age,instance2._age
You can see that, although not an instance, the state is the same.
Python single-instance mode