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 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()

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

时间: 2024-08-06 22:06:22

python单例模式的实现的相关文章

python学习笔记-Day8 下 (特殊方法、iter方法、super方法、有序字典实现、python单例模式)

使用特殊方法实现字典 # 使用像字典 dic['xx'] 带中括号的类使用 # 简要介绍 class Foo: # ① 对象[xx] 调用的方法 def __getitem__(self, item): return 'getitem' # ② 对象[xx] = xxx 调用的方法 def __setitem__(self, key, value): return 'setitem' # ③ del 对象[xx] 调用的方法 def __delitem__(self, key): return

Python单例模式剖析

在聊这之前我们首先要明确的是,单例模式在实际中的意义以及在python中具有实现的价值? 当前,相信有很多人支持单例模式,也有不少人反对,尤其是在python中,目前依旧具有很大的争议性.我们要在评论之前首先要了解单例模式 什么是单例模式? 顾名思义:就是单个模式 单例模式是一种常见的软件设置模式,在它的核心结构中只包含一个被称为单例类的特殊类,通过单例模式可以保证系统中的一个类只有一个实例而且该实例易于外界访问,从而方便对实例个数的控制并节约系统资源.如果希望在系统中某个对象只能存在一个,单例

Python单例模式

1.单例模式介绍 单例模式,也叫单子模式,是一种常用的软件设计模式.在应用这个模式时, 单例对象的类必须保证只有一个实例存在.许多时候整个系统只需要拥有一个 全局对象,这样有利于我们协调系统整体的行为. --以上来自维基百科 从定义上来看,这会是一个很有用的避免冲突的设计模式,相当于把所有同样资源的调用 都交给了一个资源代理.那么 Python 中该如何实现这一模式呢? #!/usr/bin/env python # _*_ coding:utf-8 _*_ # Author: enzhi.wa

python——单例模式

单例模式(Singleton Pattern)是一种常用的软件设计模式,该模式的主要目的是确保某一个类只有一个实例存在. 当你希望在整个系统中,某个类只能出现一个实例时,单例对象就能派上用场. 比如,某个服务器程序的配置信息存放在一个文件中,客户端通过一个 AppConfig 的类来读取配置文件的信息. 如果在程序运行期间,有很多地方都需要使用配置文件的内容,也就是说,很多地方都需要创建 AppConfig 对象的实例, 这就导致系统中存在多个 AppConfig 的实例对象,而这样会严重浪费内

设计模式(Python)-单例模式

本系列文章是希望将软件项目中最常见的设计模式用通俗易懂的语言来讲解清楚,并通过Python来实现,每个设计模式都是围绕如下三个问题: 为什么?即为什么要使用这个设计模式,在使用这个模式之前存在什么样的问题? 是什么?通过Python语言来去实现这个设计模式,用于解决为什么中提到的问题. 怎么用?理解了为什么我们也就基本了解了什么情况下使用这个模式,不过在这里还是会细化使用场景,阐述模式的局限和优缺点. 这一篇我们先来看看单例模式.单例模式是设计模式中逻辑最简单,最容易理解的一个模式,简单到只需要

Python 单例模式(3种方式)

方式一: # 单例模式: # 实现目的:实例化多次,得到的实例是同一个,就是同一个对象,同一个名称空间(更加节省空间) ####################################方式一:在类内部定义一个类方法################################# import settings class Mysql: __instance=None #定义一个变量,来接收实例化对象,方便下面做判断 def __init__(self,ip,port): self.ip

python单例模式控制成只初始化一次,常规型的python单例模式在新式类和经典类中的区别。

单例模式的写法非常多,但常规型的单例模式就是这样写的,各种代码可能略有差异,但核心就是要搞清楚类属性 实例属性,就很容易写出来,原理完全一模一样. 如下: 源码: class A(object): def __new__(cls, *args, **kwargs): if not hasattr(cls, '__inst'): print('执行new') obj = super(A, cls).__new__(cls) setattr(cls, '__inst', obj) return ob

Python单例模式的4种实现方法

#-*- encoding=utf-8 -*- print '----------------------方法1--------------------------' #方法1,实现__new__方法 #并在将一个类的实例绑定到类变量_instance上, #如果cls._instance为None说明该类还没有实例化过,实例化该类,并返回 #如果cls._instance不为None,直接返回cls._instance class Singleton(object): def __new__(

Python 单例模式

class Singleton(object): def __new__(cls, *args, **kw): if not hasattr(cls, '_instance'): orig = super(Singleton, cls) cls._instance = orig.__new__(cls, *args, **kw) return cls._instance