Python下singleton模式的实现方法


Posted in Python onJuly 16, 2014

很多开发人员在刚开始学Python 时,都考虑过像 c++ 那样来实现 singleton 模式,但后来会发现 c++ 是 c++,Python 是 Python,不能简单的进行模仿。

Python 中常见的方法是借助 global 变量,或者 class 变量来实现单件。本文就介绍以decorator来实现 singleton 模式的方法。示例代码如下:

##----------------------- code begin -----------------------

# -*- coding: utf-8 -*-
def singleton(cls):
"""Define a class with a singleton instance."""
instances = {}
def getinstance(*args, **kwds):
return instances.setdefault(cls, cls(*args, **kwds))
return getinstance
 
##1 未来版Python支持Class Decorator时可以这样用
class Foo(object):
def __init__(self, attr=1):
self.attr = attr

Foo = singleton( Foo ) ##2 2.5及之前版不支持Class Decorator时可以这样用

if __name__ == "__main__":
ins1 = Foo(2) # 等效于: ins1 = singleton(Foo)(2)
print "Foo(2) -> id(ins)=%d, ins.attr=%d, %s" % (id(ins1), ins1.attr, ('error', 'ok')[ins1.attr == 2])
ins2 = Foo(3)
print "Foo(3) -> id(ins)=%d, ins.attr=%d, %s" % (id(ins2), ins2.attr, ('error', 'ok')[ins2.attr == 2])
ins2.attr = 5
print "ins.attr=5 -> ins.attr=%d, %s" % (ins2.attr, ('error', 'ok')[ins2.attr == 5])
 
##------------------------ code end ------------------------

输出:

Foo(2) -> id(ins)=19295376, ins.attr=2, ok
Foo(3) -> id(ins)=19295376, ins.attr=2, ok
ins.attr=5 -> ins.attr=5, ok
Python 相关文章推荐
在Python中使用cookielib和urllib2配合PyQuery抓取网页信息
Apr 25 Python
python MySQLdb使用教程详解
Mar 20 Python
Python进阶之@property动态属性的实现
Apr 01 Python
python basemap 画出经纬度并标定的实例
Jul 09 Python
python try except返回异常的信息字符串代码实例
Aug 15 Python
Python dict和defaultdict使用实例解析
Mar 12 Python
Python requests.post方法中data与json参数区别详解
Apr 30 Python
浅谈pymysql查询语句中带有in时传递参数的问题
Jun 05 Python
如何以Winsows Service方式运行JupyterLab
Aug 30 Python
用python写PDF转换器的实现
Oct 29 Python
Python APScheduler执行使用方法详解
Dec 10 Python
使用python求解迷宫问题的三种实现方法
Mar 17 Python
python的迭代器与生成器实例详解
Jul 16 #Python
Python的内存泄漏及gc模块的使用分析
Jul 16 #Python
Python的垃圾回收机制深入分析
Jul 16 #Python
python中将字典转换成其json字符串
Jul 16 #Python
记录Django开发心得
Jul 16 #Python
Python实现动态添加类的属性或成员函数的解决方法
Jul 16 #Python
Python重新引入被覆盖的自带function
Jul 16 #Python
You might like
wiki-shan写的php在线加密的解密程序
2008/09/07 PHP
PHP执行批量mysql语句的解决方法
2013/05/02 PHP
wamp下修改mysql访问密码的解决方法
2013/05/07 PHP
php添加数据到xml文件的简单例子
2016/09/08 PHP
ie6下png图片背景不透明的解决办法使用js实现
2013/01/11 Javascript
理解JAVASCRIPT中hasOwnProperty()的作用
2013/06/05 Javascript
轻松实现javascript图片轮播特效
2016/01/13 Javascript
BootStrap CSS全局样式和表格样式源码解析
2017/01/20 Javascript
JavaScript中Promise的使用详解
2017/02/26 Javascript
微信小程序中的swiper组件详解
2017/04/14 Javascript
打字效果动画的4种实现方法(超简单)
2017/10/18 Javascript
Emberjs 通过 axios 下载文件的方法
2019/09/03 Javascript
JS替换字符串中指定位置的字符(多种方法)
2020/05/28 Javascript
vue常用高阶函数及综合实例
2021/02/25 Vue.js
[01:21]DOTA2周边文化主题展 神秘商店火热开售
2017/07/30 DOTA
python笔记(2)
2012/10/24 Python
python统计一个文本中重复行数的方法
2014/11/19 Python
Python爬虫获取整个站点中的所有外部链接代码示例
2017/12/26 Python
Python实现简单文本字符串处理的方法
2018/01/22 Python
Python求两点之间的直线距离(2种实现方法)
2019/07/07 Python
使用python画社交网络图实例代码
2019/07/10 Python
django页面跳转问题及注意事项
2019/07/18 Python
大数据分析用java还是Python
2020/07/06 Python
python实现图像高斯金字塔的示例代码
2020/12/11 Python
解决pycharm修改代码后第一次运行不生效的问题
2021/02/06 Python
skyn ICELAND官网:冰岛成分天然护肤品
2020/08/24 全球购物
南京软件公司的.net程序员笔试题
2014/08/31 面试题
党员学习十八大感想
2014/01/17 职场文书
教师业务培训方案
2014/05/01 职场文书
节能减耗标语
2014/06/21 职场文书
企业委托书范本
2014/09/13 职场文书
12.4全国法制宣传日活动方案
2014/11/02 职场文书
党的群众路线教育实践活动个人对照检查材料(四风)
2014/11/05 职场文书
公司副总经理岗位职责
2015/04/08 职场文书
预备党员转正意见
2015/06/01 职场文书
2015中学政教处工作总结
2015/07/22 职场文书