首页 > 代码库 > python单例模式的实现
python单例模式的实现
有些情况下我们需要单例模式来减少程序资源的浪费,在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 from10 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 check16 IOLoop._instance = IOLoop()17 return IOLoop._instance18 19 @staticmethod20 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 create28 an `IOLoop` on demand, but you may want to call `install` to use29 a custom subclass of `IOLoop`.30 """31 assert not IOLoop.initialized()32 IOLoop._instance = self33 34 @staticmethod35 def clear_instance():36 """Clear the global `IOLoop` instance.37 38 .. versionadded:: 4.039 """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()
上面贴的源码类中其余的几个方法是和单例模式配套使用的,他们一起实现了单例的功能
python单例模式的实现
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。