python单例模式的实现

本文介绍Python中使用单例模式减少资源浪费的方法,并以Tornado框架IOLoop类为例,详细解析其实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

有些情况下我们需要单例模式来减少程序资源的浪费,在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()

上面贴的源码类中其余的几个方法是和单例模式配套使用的,他们一起实现了单例的功能

转载于:https://www.cnblogs.com/kennyhr/p/3937097.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值