In some cases we need a singleton pattern to reduce the waste of program resources, and the implementation of Singleton mode is also convenient in the Python language.
I now take the tornado framework of the implementation of the Ioloop class singleton mode, for example, interested can see the source of their own
1 classIoloop (configurable):2 ...3 4 @staticmethod5 definstance ():6 """Returns a global ' Ioloop ' instance.7 8 Most applications has a single, and the global ' Ioloop ' running on the9 main thread. use the This method to get the this instance fromTen another thread. To get the current thread ' s ' ioloop ', use ' current ' () '. One """ A if notHasattr (Ioloop,"_instance"): - With Ioloop._instance_lock: - if notHasattr (Ioloop,"_instance"): the #New instance after double check -Ioloop._instance =Ioloop () - returnioloop._instance - + @staticmethod - definitialized (): + """Returns True if the singleton instance has been created.""" A returnHasattr (Ioloop,"_instance") at - defInstall (self): - """installs this ' Ioloop ' object as the singleton instance. - - This was normally not necessary as ' instance () ' would create - An ' ioloop ' in demand, but if you could want to call ' install ' to use in a custom subclass of ' Ioloop '. - """ to assert notioloop.initialized () +Ioloop._instance = Self - the @staticmethod * defclear_instance (): $ """Clear the global ' Ioloop ' instance.Panax Notoginseng - .. versionadded:: 4.0 the """ + ifHasattr (Ioloop,"_instance"): A delIoloop._instance
Where the code that implements the singleton pattern is
if not " _instance " ): With ioloop._instance_lock: ifnot"_instance" ): # New instance after double check ioloop._instance = Ioloop ( ) return ioloop._instance
And the method of guaranteeing the invocation of Singleton mode is very simple:
Tornado.ioloop.IOLoop.instance (). Start ()
The above-mentioned source code class in the remaining several methods are used in conjunction with the Singleton pattern, they implemented a single example of the function
Implementation of a Python singleton pattern