有些情况下我们需要单例模式来减少程序资源的浪费,在python语言中单例模式的实现同样是方便的。
我现在以tornado框架中IOLoop类单例模式的实现来举例,有兴趣的可以自己看一下源码
1 class IOLoop(Configurable): 2 …… 3 4 @staticmethod 5 def instance(): 6 """Returns a global `IOLoop` instance. 7 8 Most applications have a single, global `IOLoop` running on the 9 main thread. Use this method to get this instance from 10 another thread. To get the current thread's `IOLoop`, use `current()`. 11 """ 12 if not hasattr(IOLoop, "_instance"): 13 with IOLoop._instance_lock: 14 if not hasattr(IOLoop, "_instance"): 15 # New instance after double check 16 IOLoop._instance = IOLoop() 17 return IOLoop._instance 18 19 @staticmethod 20 def initialized(): 21 """Returns true if the singleton instance has been created.""" 22 return hasattr(IOLoop, "_instance") 23 24 def install(self): 25 """Installs this `IOLoop` object as the singleton instance. 26 27 This is normally not necessary as `instance()` will create 28 an `IOLoop` on demand, but you may want to call `install` to use 29 a custom subclass of `IOLoop`. 30 """ 31 assert not IOLoop.initialized() 32 IOLoop._instance = self 33 34 @staticmethod 35 def clear_instance(): 36 """Clear the global `IOLoop` instance. 37 38 .. versionadded:: 4.0 39 """ 40 if hasattr(IOLoop, "_instance"): 41 del IOLoop._instance
其中实现单例模式的代码是
if not hasattr(IOLoop, "_instance"): with IOLoop._instance_lock: if not hasattr(IOLoop, "_instance"): # New instance after double check IOLoop._instance = IOLoop() return IOLoop._instance
而保证单例模式调用的方法也就很简单了:
tornado.ioloop.IOLoop.instance().start()
上面贴的源码类中其余的几个方法是和单例模式配套使用的,他们一起实现了单例的功能