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的Django框架的运行方式及处理流程
Apr 08 Python
python开启多个子进程并行运行的方法
Apr 18 Python
在Python中移动目录结构的方法
Jan 31 Python
深入解析Python设计模式编程中建造者模式的使用
Mar 02 Python
利用numpy实现一、二维数组的拼接简单代码示例
Dec 15 Python
Python+request+unittest实现接口测试框架集成实例
Mar 16 Python
Python数据结构之图的应用示例
May 11 Python
Python中常用的内置方法
Jan 28 Python
对Python中的条件判断、循环以及循环的终止方法详解
Feb 08 Python
在python image 中实现安装中文字体
May 16 Python
Kmeans均值聚类算法原理以及Python如何实现
Sep 26 Python
python 读取串口数据的示例
Nov 09 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 SQL防注入代码集合
2008/04/25 PHP
用mysql触发器自动更新memcache的实现代码
2009/10/11 PHP
利用PHP访问MySql数据库的逻辑操作以及增删改查的实例讲解
2017/08/30 PHP
php设计模式之享元模式分析【星际争霸游戏案例】
2020/03/23 PHP
代码生成器 document.write()
2007/04/15 Javascript
JavaScript 数组运用实现代码
2010/04/13 Javascript
比较新旧两个数组值得增加和删除的JS代码
2013/10/30 Javascript
For循环中分号隔开的3部分的执行顺序探讨
2014/05/27 Javascript
JavaScript中数据结构与算法(三):链表
2015/06/19 Javascript
ajax实现动态下拉框示例
2017/01/10 Javascript
快速解决vue在ios端下点击响应延时的问题
2018/08/27 Javascript
vue 项目中使用Loading组件的示例代码
2018/08/31 Javascript
vue中组件的3种使用方式详解
2019/03/23 Javascript
Python Socket编程详细介绍
2017/03/23 Python
python Celery定时任务的示例
2018/03/13 Python
Python文本统计功能之西游记用字统计操作示例
2018/05/07 Python
python pandas cumsum求累计次数的用法
2019/07/29 Python
Django框架模板用法入门教程
2019/11/04 Python
Python日志syslog使用原理详解
2020/02/18 Python
pygame实现弹球游戏
2020/04/14 Python
tensorflow从ckpt和从.pb文件读取变量的值方式
2020/05/26 Python
python中如何写类
2020/06/29 Python
django filter过滤器实现显示某个类型指定字段不同值方式
2020/07/16 Python
美国百年历史早餐食品供应商:Wolferman’s
2017/01/18 全球购物
Myprotein法国官网:欧洲第一运动营养品牌
2019/03/26 全球购物
介绍一下游标
2012/01/10 面试题
ShellScript面试题一则-ShellScript编程
2014/03/05 面试题
银行实习人员自我鉴定
2013/09/22 职场文书
仓库门卫岗位职责
2013/12/22 职场文书
夏季奶茶店创业计划书
2014/01/16 职场文书
小学教师国培感言
2014/02/08 职场文书
中学生自我评价范文
2014/02/08 职场文书
房屋买卖协议书
2014/04/10 职场文书
专科应届毕业生求职信
2014/06/04 职场文书
2016领导干部廉洁自律心得体会
2016/01/13 职场文书
maven 解包依赖项中的文件的解决方法
2022/07/15 Java/Android