参考

# 第一种方法 new 方法
class Singleton(object):
def __new__(cls,*args,**kw):
if not hasattr(cls,'_instance'):
cls._instance = super(Singleton,cls).__new__(cls,*args,**kw)
return cls._instance s1 = Singleton()
s2 = Singleton()
s1 == s2
# 第二种方法升级为元类 call 控制,实质跟方法一差不多
class SingletonMetaclass(type):
def __call__(cls,*args,**kw):
if not hasattr(cls,'_instance'):
cls._instance = super(SingletonMetaclass,cls).__call__(*args,**kw)
# cls.__init__(cls._instance,*args,**kw)
return cls._instance class Singleton(object,metaclass=SingletonMetaclass):
pass s1 = Singleton()
s2 = Singleton()
s1 == s2
# 第三种,使用装饰器
def singleton(cls,*args,**kw):
instance = {}
def get_instance():
if cls not in instance:
instance[cls] = cls.__new__(cls,*args,**kw)
return instance[cls]
return get_instance @singleton
class Singleton(object):
pass s1 = Singleton()
s2 = Singleton()
s1 == s2

线程安全

# 线程安全的 写法
# 装饰器
import threading
def Singleton(cls,*args,**kw):
instance = {}
_instance_lock = threading.Lock()
def get_instance():
if cls not in instance:
with _instance_lock:
if cls not in instance:
instance[cls] = cls.__new__(cls,*args,**kw)
cls.__init__(instance[cls],*args,**kw)
return instance[cls]
return get_instance @Singleton
class Demo(object):
pass
d1 = Demo()
d2 = Demo()
d1 is d2
# 基类
class Singleton(object):
def __new__(cls,*args,**kw):
if not hasattr(cls,'_instance'):
cls._instance = super(Singleton,cls).__new__(cls,*args,**kw)
return cls._instance s1 = Singleton()
s2 = Singleton()
print(s1 == s2)
# 升级为元类
import threading
class SingletonMetaclass(type):
def __call__(cls,*args,**kw):
_instance_lock = threading.Lock()
if not hasattr(cls,'_instance'):
with _instance_lock:
if not hasattr(cls,'_instance'):
cls._instance = cls.__new__(cls,*args,**kw)
cls.__init__(cls._instance,*args,**kw)
return cls._instance class Demo(object,metaclass=SingletonMetaclass):
pass d2 = Demo()
d3 = Demo()
d2 is d3
mysingleton.py

class Singleton(object):
def foo(self):
pass
singleton = Singleton()
将上面的代码保存在文件 mysingleton.py 中,要使用时,直接在其他文件中导入此文件中的对象,这个对象即是单例模式的对象 from mysingleton import singleton
方法四:Borg模式
利用“类变量对所有对象唯一”,即__share_state class Foo:
__share_state = {}
def __init__(self):
self.__dict__ = self.__share_state

python 单例模式总结的更多相关文章

  1. python 单例模式获取IP代理

    python 单例模式获取IP代理 tags:python python单例模式 python获取ip代理 引言:最近在学习python,先说一下我学Python得原因,一个是因为它足够好用,完成同样 ...

  2. Python 单例模式讲解

    Python 单例模式讲解 本节内容: classmethod用途 单例模式方法一 类__new__方法讲解 单例模式方法二 前言: 使用单例方法的好处:对于一个类,多次实例化会产生多个对象,若使用单 ...

  3. python单例模式的实现与优化

    python单例模式的实现与优化 阅读目录(Content) 单例模式 实现单例模式的几种方式 1.使用模块 2.使用装饰器 3.使用类 4.基于__new__方法实现(推荐使用,方便) 5.基于me ...

  4. python 单例模式

    单例模式,也叫单子模式,是一种常用的软件设计模式.在应用这个模式时,单例对象的类必须保证只有一个实例存在 用装饰器方式实现单例模式 #!/usr/bin/python # coding=utf-8 d ...

  5. Python单例模式

    1.单例模式介绍 单例模式,也叫单子模式,是一种常用的软件设计模式.在应用这个模式时, 单例对象的类必须保证只有一个实例存在.许多时候整个系统只需要拥有一个 全局对象,这样有利于我们协调系统整体的行为 ...

  6. python 单例模式的四种创建方式

    单例模式 单例模式(Singleton Pattern)是一种常用的软件设计模式,该模式的主要目的是确保某一个类只有一个实例存在.当你希望在整个系统中,某个类只能出现一个实例时,单例对象就能派上用场. ...

  7. python 单例模式的四种实现方法及注意事项

    一.模块单例 Python 的模块就是天然的单例模式,因为模块在第一次导入时,会生成 .pyc 文件,当第二次导入时,就会直接加载 .pyc 文件,而不会再次执行模块代码. #foo1.py clas ...

  8. python 单例模式,一个类只能生成唯一的一个实例,重写__new__方法详解

    单例:一个类只能生成唯一的一个实例 每个类只要被实例化了,他的私有属性 '_instance'就会被赋值,这样理解对吗 对 #方法1,实现__new__方法 #并在将一个类的实例绑定到类变量_inst ...

  9. 设计模式(Python)-单例模式

    本系列文章是希望将软件项目中最常见的设计模式用通俗易懂的语言来讲解清楚,并通过Python来实现,每个设计模式都是围绕如下三个问题: 为什么?即为什么要使用这个设计模式,在使用这个模式之前存在什么样的 ...

  10. Python单例模式的四种方法

    在这之前,先了解super()和__new__()方法 super()方法: 返回一个父类或兄弟类类型的代理对象,让你能够调用一些从继承过来的方法. 它有两个典型作用: a. 在单继承的类层次结构中, ...

随机推荐

  1. hibernate中持久化对象的生命周期(转载)

    三态的基本概念 1, 临时状态(Transient):也叫自由态,只存在于内存中,而在数据库中没有相应数据.用new创建的对象,它没有持久化,没有处于Session中,处于此状态的对象叫临时对象: 2 ...

  2. jQuery 方式模拟提交表单

    //add test moudle define(function(require , exports , module) { //=========== 不使用模块化只使用如下代码即可 start ...

  3. HDOJ5547 SudoKu

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5547 题目大意:填数独... 思路:爆搜 #include <stdio.h> #incl ...

  4. 【题解】 AtCoder ARC 076 F - Exhausted? (霍尔定理+线段树)

    题面 题目大意: 给你\(m\)张椅子,排成一行,告诉你\(n\)个人,每个人可以坐的座位为\([1,l]\bigcup[r,m]\),为了让所有人坐下,问至少还要加多少张椅子. Solution: ...

  5. 关于 atcoder 页面美化的 css

    使用方式 把下面代码加入 ESI Stylish 即可. 这是一个 chrome 的插件,可以翻\(~\)墙(或者不需要)去下载. 这是本人瞎魔改的... 代码 Update on 12-17 \(a ...

  6. android TextView字体设置最少占多少行. 及其 Java String 字符串操作 . .

    ①  字体设置: 修改代码 :  GridViewActivity.java priceTv为 TextView priceTv.setMaxLines(3); //当多与7个字fu的时候 , 其余字 ...

  7. 让自己的网站实现在线编辑office文档

    我们可以通过Office Web Apps(OWA)来实现在线编辑word,excel,power point, one note,并集成到自己的网站里去.   1 准备工作 1.1 操作系统 安装了 ...

  8. 20165223 实验四 Android开发基础

    实验四 Android开发基础 目录 一.实验报告封面 二.具体实验内容 (一)Android Stuidio的安装测试 (二)Activity测试 (三)UI测试 (四)布局测试 (五)教材代码测试 ...

  9. Ubuntu常用软件安装(小集合)

    跨平台系列汇总:http://www.cnblogs.com/dunitian/p/4822808.html#linux Linux包系列的知识:https://www.cnblogs.com/dun ...

  10. golang语言并发与并行——goroutine和channel的详细理解(一)

    如果不是我对真正并行的线程的追求,就不会认识到Go有多么的迷人. Go语言从语言层面上就支持了并发,这与其他语言大不一样,不像以前我们要用Thread库 来新建线程,还要用线程安全的队列库来共享数据. ...