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


Posted in Python onAugust 14, 2017

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

方法一 

import threading 
 
class Singleton(object): 
  __instance = None 
 
  __lock = threading.Lock()  # used to synchronize code 
 
  def __init__(self): 
    "disable the __init__ method" 
 
  @staticmethod 
  def getInstance(): 
    if not Singleton.__instance: 
      Singleton.__lock.acquire() 
      if not Singleton.__instance: 
        Singleton.__instance = object.__new__(Singleton) 
        object.__init__(Singleton.__instance) 
      Singleton.__lock.release() 
    return Singleton.__instance

 1.禁用__init__方法,不能直接创建对象。

 2.__instance,单例对象私有化。

 3.@staticmethod,静态方法,通过类名直接调用。

 4.__lock,代码锁。

 5.继承object类,通过调用object的__new__方法创建单例对象,然后调用object的__init__方法完整初始化。 

6.双重检查加锁,既可实现线程安全,又使性能不受很大影响。 

方法二:使用decorator

#encoding=utf-8 
def singleton(cls): 
  instances = {} 
  def getInstance(): 
    if cls not in instances: 
      instances[cls] = cls() 
    return instances[cls] 
  return getInstance 
 
@singleton 
class SingletonClass: 
  pass 
 
if __name__ == '__main__': 
  s = SingletonClass() 
  s2 = SingletonClass() 
  print s 
  print s2

也应该加上线程安全  

附:性能没有方法一高

import threading 
 
class Sing(object): 
  def __init__(): 
    "disable the __init__ method" 
 
  __inst = None # make it so-called private 
 
  __lock = threading.Lock() # used to synchronize code 
 
  @staticmethod 
  def getInst(): 
    Sing.__lock.acquire() 
    if not Sing.__inst: 
      Sing.__inst = object.__new__(Sing) 
      object.__init__(Sing.__inst) 
    Sing.__lock.release() 
    return Sing.__inst

以上就是Python单例模式的实例详解,如有疑问请留言或者到本站的社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

Python 相关文章推荐
举例讲解Python编程中对线程锁的使用
Jul 12 Python
Python中Django发送带图片和附件的邮件
Mar 31 Python
浅谈Python由__dict__和dir()引发的一些思考
Oct 30 Python
python实现kNN算法
Dec 20 Python
python+opencv实现动态物体追踪
Jan 09 Python
利用Python+Java调用Shell脚本时的死锁陷阱详解
Jan 24 Python
python pandas实现excel转为html格式的方法
Oct 23 Python
Django+zTree构建组织架构树的方法
Aug 21 Python
基于jupyter代码无法在pycharm中运行的解决方法
Apr 21 Python
k-means & DBSCAN 总结
Apr 27 Python
解决Pytorch半精度浮点型网络训练的问题
May 24 Python
Python标准库之typing的用法(类型标注)
Jun 02 Python
Python基于Matplotlib库简单绘制折线图的方法示例
Aug 14 #Python
python使用super()出现错误解决办法
Aug 14 #Python
Python SQLite3数据库日期与时间常见函数用法分析
Aug 14 #Python
python itchat实现微信自动回复的示例代码
Aug 14 #Python
Python编程实现控制cmd命令行显示颜色的方法示例
Aug 14 #Python
django 创建过滤器的实例详解
Aug 14 #Python
django创建自定义模板处理器的实例详解
Aug 14 #Python
You might like
php UBB 解析实现代码
2011/11/27 PHP
php伪静态之APACHE篇
2014/06/02 PHP
getJSON跨域SyntaxError问题分析
2014/08/07 PHP
关闭浏览器窗口弹出提示框并且可以控制其失效
2014/04/15 Javascript
详解JavaScript数组和字符串中去除重复值的方法
2016/03/07 Javascript
关于vue-router路径计算问题
2017/05/10 Javascript
Javascript中this关键字指向问题的测试与详解
2017/08/11 Javascript
利用nodeJs anywhere搭建本地服务器环境的方法
2018/05/12 NodeJs
深入理解使用Vue实现Context-Menu的思考与总结
2019/03/09 Javascript
Layui 解决表格异步调用后台分页的问题
2019/10/26 Javascript
jQuery实现购物车全功能
2021/01/11 jQuery
Python简单读取json文件功能示例
2017/11/30 Python
Django使用HttpResponse返回图片并显示的方法
2018/05/22 Python
django+xadmin+djcelery实现后台管理定时任务
2018/08/14 Python
Python实现查找最小的k个数示例【两种解法】
2019/01/08 Python
Python超越函数积分运算以及绘图实现代码
2019/11/20 Python
Python3爬虫关于代理池的维护详解
2020/07/30 Python
python使用多线程查询数据库的实现示例
2020/08/17 Python
Python Pandas数据分析工具用法实例
2020/11/05 Python
BeautifulSoup获取指定class样式的div的实现
2020/12/07 Python
几款主流好用的富文本编辑器(所见即所得常用编辑器)介绍
2021/03/17 Javascript
CSS3 3D制作实战案例分析
2016/09/18 HTML / CSS
html5 canvas移动浏览器上实现图片压缩上传
2016/03/11 HTML / CSS
欧洲最大的美妆零售网站:Feelunique
2017/01/14 全球购物
如何利用XMLHTTP检测URL及探测服务器信息
2013/11/10 面试题
公司人力资源的自我评价
2014/01/02 职场文书
中学教师管理制度
2014/01/14 职场文书
员工晚婚的请假条
2014/02/08 职场文书
竞聘书格式及范文
2014/03/31 职场文书
工程承包协议书
2014/04/22 职场文书
工伤事故赔偿协议书
2014/10/27 职场文书
财产分割协议书范本
2014/11/03 职场文书
2014年医生工作总结
2014/11/21 职场文书
2015年安全工作总结范文
2015/04/02 职场文书
结婚通知短信大全
2015/04/17 职场文书
Redis sentinel哨兵集群的实现步骤
2022/07/15 Redis