Python单例模式实例分析

yipeiwu_com5年前Python基础

本文实例讲述了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 FTP文件定时自动下载实现过程解析

这篇文章主要介绍了Python FTP文件定时自动下载实现过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 一、需求:   某数...

python验证码识别教程之利用滴水算法分割图片

python验证码识别教程之利用滴水算法分割图片

滴水算法概述 滴水算法是一种用于分割手写粘连字符的算法,与以往的直线式地分割不同 ,它模拟水滴的滚动,通过水滴的滚动路径来分割字符,可以解决直线切割造成的过分分割问题。 引言 之前提过对...

用Python制作检测Linux运行信息的工具的教程

在这篇文章里,我们将会探索如何使用Python语言作为一个工具来检测Linux系统各种运行信息。让我们一起来学习吧。 哪种Python? 当我提到Python时,我一般是指CPython...

selenium+python实现自动化登录的方法

Selenium Python 提供了一个简单的API 便于我们使用 Selenium WebDriver编写 功能/验收测试。 通过Selenium Python的API,你可以直观地...

Python Paramiko模块的使用实际案例

本文研究的主要是Python Paramiko模块的使用的实例,具体如下。 Windows下有很多非常好的SSH客户端,比如Putty。在python的世界里,你可以使用原始套接字和一些...