Python单例模式实例分析


Posted in Python onJanuary 14, 2015

本文实例讲述了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获取当前时间的方法
Jan 14 Python
ptyhon实现sitemap生成示例
Mar 30 Python
纯Python开发的nosql数据库CodernityDB介绍和使用实例
Oct 23 Python
详细解析Python中__init__()方法的高级应用
May 11 Python
Python实现统计文本文件字数的方法
May 05 Python
Python装饰器知识点补充
May 28 Python
Python3内置模块之json编解码方法小结【推荐】
Dec 09 Python
pytorch实现mnist分类的示例讲解
Jan 10 Python
Python中实现输入超时及如何通过变量获取变量名
Jan 18 Python
PyCharm License Activation激活码失效问题的解决方法(图文详解)
Mar 12 Python
python 提高开发效率的5个小技巧
Oct 19 Python
Python使用scapy模块发包收包
May 07 Python
python文件读写操作与linux shell变量命令交互执行的方法
Jan 14 #Python
Python中使用Tkinter模块创建GUI程序实例
Jan 14 #Python
更改Python命令行交互提示符的方法
Jan 14 #Python
Python的迭代器和生成器使用实例
Jan 14 #Python
python实现带验证码网站的自动登陆实现代码
Jan 12 #Python
Python三元运算实现方法
Jan 12 #Python
Python中的True,False条件判断实例分析
Jan 12 #Python
You might like
php生成随机数或者字符串的代码
2008/09/05 PHP
PHP OPCode缓存 APC详细介绍
2010/10/12 PHP
PHP实现货币换算的方法
2014/11/29 PHP
php通过array_push()函数添加多个变量到数组末尾的方法
2015/03/18 PHP
支付宝服务窗API接口开发php版本
2016/07/20 PHP
phpmailer绑定邮箱的实现方法
2016/12/01 PHP
js判断输入是否为正整数、浮点数等数字的函数代码
2010/11/17 Javascript
Javascript 判断是否存在函数的方法
2013/01/03 Javascript
connect中间件session、cookie的使用方法分享
2014/06/17 Javascript
javascript中bind函数的作用实例介绍
2014/09/28 Javascript
javascript实现全角转半角的方法
2016/01/23 Javascript
Javascript操作表单实例讲解(下)
2016/06/20 Javascript
Javascript实现时间倒计时效果
2017/07/15 Javascript
import与export在node.js中的使用详解
2017/09/28 Javascript
详解vue-admin和后端(flask)分离结合的例子
2018/02/12 Javascript
解决iview打包时UglifyJs报错的问题
2018/03/07 Javascript
在vue中封装方法以及多处引用该方法详解
2020/08/14 Javascript
Python中optparse模块使用浅析
2015/01/01 Python
Python内置模块logging用法实例分析
2018/02/12 Python
matplotlib实现热成像图colorbar和极坐标图的方法
2018/12/13 Python
python随机在一张图像上截取任意大小图片的方法
2019/01/24 Python
解决Python中定时任务线程无法自动退出的问题
2019/02/18 Python
python如何解析复杂sql,实现数据库和表的提取的实例剖析
2020/05/15 Python
美国时尚大码女装购物网站:Avenue
2019/05/24 全球购物
Dr. Martens马汀博士德国官网:马丁靴鼻祖
2019/12/26 全球购物
门卫人员岗位职责
2013/12/24 职场文书
先进事迹报告会感言
2014/01/24 职场文书
售后服务经理岗位职责
2014/02/25 职场文书
学校三八妇女节活动情况总结
2014/03/09 职场文书
高三学习决心书
2014/03/11 职场文书
模范教师材料大全
2014/12/16 职场文书
幼儿园感谢信
2015/01/21 职场文书
三峡导游词
2015/01/31 职场文书
酒店客房服务员岗位职责
2015/04/09 职场文书
python 标准库原理与用法详解之os.path篇
2021/10/24 Python
Spring中bean集合注入的方法详解
2022/07/07 Java/Android