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程序设计有所帮助。

(0)

相关推荐

  • Python设计模式中单例模式的实现及在Tornado中的应用

    单例模式的实现方式 将类实例绑定到类变量上 class Singleton(object): _instance = None def __new__(cls, *args): if not isinstance(cls._instance, cls): cls._instance = super(Singleton, cls).__new__(cls, *args) return cls._instance 但是子类在继承后可以重写__new__以失去单例特性 class D(Singleto

  • Python单例模式实例详解

    本文实例讲述了Python单例模式.分享给大家供大家参考,具体如下: 单例模式:保证一个类仅有一个实例,并提供一个访问他的全局访问点. 实现某个类只有一个实例的途径: 1,让一个全局变量使得一个对象被访问,但是他不能防止外部实例化多个对象. 2,让类自身保存他的唯一实例,这个类可以保证没有其他实例可以被创建. 多线程时的单例模式:加锁-双重锁定 饿汉式单例类:在类被加载时就将自己实例化(静态初始化).其优点是躲避了多线程访问的安全性问题,缺点是提前占用系统资源. 懒汉式单例类:在第一次被引用时,

  • 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.__instanc

  • 5种Python单例模式的实现方式

    本文为大家分享了Python创建单例模式的5种常用方法,供大家参考,具体内容如下 所谓单例,是指一个类的实例从始至终只能被创建一次. 方法1: 如果想使得某个类从始至终最多只有一个实例,使用__new__方法会很简单.Python中类是通过__new__来创建实例的: class Singleton(object): def __new__(cls,*args,**kwargs): if not hasattr(cls,'_inst'): cls._inst=super(Singleton,cl

  • 详解python单例模式与metaclass

    单例模式的实现方式 将类实例绑定到类变量上 class Singleton(object): _instance = None def __new__(cls, *args): if not isinstance(cls._instance, cls): cls._instance = super(Singleton, cls).__new__(cls, *args) return cls._instance 但是子类在继承后可以重写__new__以失去单例特性 class D(Singleto

  • 常见的在Python中实现单例模式的三种方法

    单例模式是一种常用的软件设计模式.在它的核心结构中只包含一个被称为单例类的特殊类.通过单例模式可以保证系统中一个类只有一个实例而且该实例易于外界访问,从而方便对实例个数的控制并节约系统资源.如果希望在系统中某个类的对象只能存在一个,单例模式是最好的解决方案. 单例模式的要点有三个:一是某个类只能有一个实例:二是它必须自行创建这个实例:三是它必须自行向整个系统提供这个实例.在Python中,单例模式有以下几种实现方式. 方法一.实现__new__方法,然后将类的一个实例绑定到类变量_instanc

  • Python设计模式之单例模式实例

    注:使用的是Python 2.7. 一个简单实现 复制代码 代码如下: class Foo(object):    __instance = None    def __init__(self):        pass    @classmethod    def getinstance(cls):        if(cls.__instance == None):            cls.__instance = Foo()        return cls.__instance

  • Python单例模式实例分析

    本文实例讲述了Python单例模式的使用方法.分享给大家供大家参考.具体如下: 方法一 复制代码 代码如下: import threading    class Singleton(object):      __instance = None        __lock = threading.Lock()   # used to synchronize code        def __init__(self):          "disable the __init__ method&

  • python单例模式实例解析

    本文实例为大家分享了python单例模式的具体代码,供大家参考,具体内容如下 多次实例化的结果指向同一个实例 单例模式实现方式 方式一: import settings class MySQL: __instance = None def __init__(self, ip, port): self.ip = ip self.port = port @classmethod def from_conf(cls): if cls.__instance is None: cls.__instance

  • php设计模式之单例模式实例分析

    本文实例讲述了php设计模式之单例模式.分享给大家供大家参考.具体分析如下: 单例模式(职责模式): 简单的说,一个对象(在学习设计模式之前,需要比较了解面向对象思想)只负责一个特定的任务: 单例类: 1.构造函数需要标记为private(访问控制:防止外部代码使用new操作符创建对象),单例类不能在其他类中实例化,只能被其自身实例化: 2.拥有一个保存类的实例的静态成员变量 3.拥有一个访问这个实例的公共的静态方法(常用getInstance()方法进行实例化单例类,通过instanceof操

  • Python图算法实例分析

    本文实例讲述了Python图算法.分享给大家供大家参考,具体如下: #encoding=utf-8 import networkx,heapq,sys from matplotlib import pyplot from collections import defaultdict,OrderedDict from numpy import array # Data in graphdata.txt: # a b 4 # a h 8 # b c 8 # b h 11 # h i 7 # h g

  • python任务调度实例分析

    本文实例讲述了python任务调度实现方法.分享给大家供大家参考.具体如下: 方法1: import sched, time import os s = sched.scheduler(time.time, time.sleep) #scheduler的两个参数用法复杂,可以不做任何更改 def playmusic(x): os.system(x) def jobtodo(): tmlist = [2011,8,11,22,15,0,0,0,0] x1=time.mktime(tmlist) x

  • Java设计模式之单例模式实例分析

    本文实例讲述了Java设计模式之单例模式.分享给大家供大家参考,具体如下: 单例模式:(Singleton Pattern)是一个比较简单的模式,其定义如下: Ensure a class has only one instance, and provide a global point of access to it.(确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例) 单例模式,很简单的一个模式.其实在android开发中,很多地方都会用到单例模式,比如某些工具类.Json数

  • PHP单例模式实例分析【防继承,防克隆操作】

    本文实例讲述了PHP单例模式.分享给大家供大家参考,具体如下: <?php //单列模式 // //1.普通类 // class singleton{ // } // $s1 = new singleton(); // $s2 = new singleton(); // //注意,2个变量是同1个对象的时候才全等 // if ($s1 === $s2) { // echo '是一个对象'; // }else{ // echo '不是一个对象'; // } // //2.封锁new操作 // cl

  • Python数学形态学实例分析

    本文实例讲述了Python数学形态学.分享给大家供大家参考,具体如下: 一 原始随机图像 1.代码 import numpy as np import matplotlib.pyplot as plt square = np.zeros((32,32))#全0数组 square[10:20,10:20]=1#把其中一部分设置为1 x, y =(32*np.random.random((2,15))).astype(np.int)#随机位置 square[x,y]=1#把随机位置设置为1 plt.

  • python单例模式原理与创建方法实例分析

    本文实例讲述了python单例模式原理与创建方法.分享给大家供大家参考,具体如下: 1. 单例是什么 举个常见的单例模式例子,我们日常使用的电脑上都有一个回收站,在整个操作系统中,回收站只能有一个实例,整个系统都使用这个唯一的实例,而且回收站自行提供自己的实例.因此回收站是单例模式的应用. 确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例,这个类称为单例类,单例模式是一种对象创建型模式. 2. 创建单例-保证只有1个对象 # 实例化一个单例 class Singleton(obj

随机推荐