Before we talk about this, let's first make it clear that the meaning of the singleton pattern in practice and the value of the implementation in Python.
At present, I believe there are many people who support the singleton model, and many people oppose it, especially in Python, which is still very controversial. We need to understand the singleton mode first before commenting.
What is a singleton mode?
As the name implies: is a single mode
Singleton mode is a common software setup mode, in its core structure contains only a special class called Singleton class, through a singleton mode can ensure that a class in the system only one instance and the instance is easy to access outside, so as to facilitate the control of the number of instances and save system resources. Singleton mode is the best solution if you want only one object in the system to exist.
The main points of the singleton pattern are three categories
- A class can have only one instance
- It must create this instance
- It must provide this instance to the entire system on its own
But from a specific point of view, can be divided into three points
- A singleton pattern class can only provide a private constructor
- The class definition contains a static private object of the class
- The class provides a static common function for creating or fetching static private objects of its own
First, instance control
Singleton mode prevents other objects from instantiating copies of their own singleton objects, ensuring that all objects have access to unique instances.
Second, flexibilityBecause classes control the instantiation process, classes can flexibly change the instantiation process.Disadvantages:
first, the costAlthough the number is small, there will still be some overhead if you want to check for instances of the class every time the object requests a reference. This problem can be resolved by using static initialization.
Ii. Possible confusion of developmentWhen using singleton objects, especially those defined in a class library, developers must remember that they cannot use
NewKeyword to instantiate the object. Because library source code may not be accessible, application developers may unexpectedly find themselves unable to instantiate this class directly.
Iii. Object LifetimeThe problem of deleting a single object cannot be resolved. In a language that provides memory management, such as a. NET framework-based language, only a singleton class can cause an instance to be deallocated because it contains a private reference to the instance. In some languages, such as C + +, other classes can delete object instances, but this results in a floating reference in a singleton class. Several common ways
Simply construct a singleton pattern with the feature oriented
# ########### Singleton class definition ########## #class Foo (object): __instance = None @staticmethod def Singleton (): if Foo.__instance: return foo.__instance else: foo.__instance = Foo () return foo.__instance # ###### ##### Get instance ########## #obj = Foo.singleton ()
Simple application of Singleton mode when used in Web interface
1 #!/usr/bin/env python2 #Coding:utf-83 fromWsgiref.simple_serverImportMake_server4 5 ############ Singleton class definition ###########6 classDBHelper (object):7 8 __instance=None9 Ten def __init__(self): OneSelf.hostname ='1.1.1.1' ASelf.port = 3306 -Self.password ='pwd' -Self.username ='Root' the - @staticmethod - defSingleton (): - ifDBHelper.__instance: + returnDBHelper.__instance - Else: +DBHelper.__instance=DBHelper () A returnDBHelper.__instance at - deffetch (self): - #connecting to a database - #Splicing SQL statements - #Operation - Pass in - defCreate (self): to #connecting to a database + #Splicing SQL statements - #Operation the Pass * $ defRemove (self):Panax Notoginseng #connecting to a database - #Splicing SQL statements the #Operation + Pass A the defModify (self): + #connecting to a database - #Splicing SQL statements $ #Operation $ Pass - - the classHandler (object): - Wuyi defindex (self): theobj =Dbhelper.singleton () - PrintID (Single) Wu obj.create () - return 'Index' About $ defNews (self): - return 'News' - - A defrunserver (environ, start_response): +Start_response ('OK', [('Content-type','text/html')]) theURL = environ['Path_info'] -temp = Url.split ('/') [1] $obj =Handler () theIs_exist =hasattr (obj, temp) the ifis_exist: theFunc =getattr (obj, temp) theRET =func () - returnret in Else: the return '404 Not Found' the About if __name__=='__main__': thehttpd = Make_server ("', 8001, Runserver) the Print "serving HTTP on port 8001 ..." the Httpd.serve_forever () + -Web application Example-Singleton modeWeb Singleton mode
But what we need to be aware of is:
The Special method __new__ is a meta-constructor that will be called whenever an object must be instantiated by the factory class. The __new__ method must return an instance of a class, so it can modify the class before or after the object is created.
Because __init__ is not implicitly called in subclasses, __new__ can be used to determine that initialization constructs have been completed at the entire class level. __NEW__ is a response to an implicit initialization requirement for an object's state, allowing an initialization to be defined at a lower level than __init__, which is always called.
The __new__ () method is more like a real constructor than __init__ (). With the unification of classes and types, the user can derive from the built-in type, thus requiring a way to instantiate an immutable object, such as a derived string, in which case the interpreter invokes the __new__ () method of the class, a static method, and the passed arguments are generated when the class instantiates the operation. __NEW__ () invokes the parent class's __new__ () to create the object (up proxy)
__new__ must return a valid instance, so that when the interpreter calls __init__ (), it can pass the instance as self to him. Call the parent class's __new__ () to create the object, just as you would use the New keyword in another language
Summary
Simple interest mode exists to ensure that only a single instance exists in the current memory, avoiding memory waste!!!
Anatomy of a Python singleton pattern