Python中单例模式总结


Posted in Python onFebruary 20, 2018

一、单例模式

    a、单例模式分为四种:文件,类,基于__new__方法实现单例模式,基于metaclass方式实现

    b、类实现如下:

class Sigletion(objects):
  import time
  def __init__(self):
    time.sleep(1)
  @classmethod
  def instance(cls,*args,**kwargs)
    if not hasattr(Sigletion,'_instance'):
      Sigletion._instance=Sigletion(*args,**kwargs)
    return Sigletion._instance

import threading

daf task(arg):
  obj=Sigletion.instance()
  print(obj)

for i in range(10):
  t=threading.Thread(target=task,args=[i,])
  t.start()

    c、基于__new__方法实现单例模式

import time
import threading
class Singleton(object):
  _instance_lock=threading.Lock()
  def __init__(self):
    pass
  def __new__(cls, *args, **kwargs):
    if not hasattr(Singleton,"_instance"):
      with Singleton._instance_lock:
        if not hasattr(Singleton,"_instance"):
          Singleton._instance=object.__new__(cls,*args,**kwargs)
    return Singleton._instance

obj1=Singleton()
obj2=Singleton()
print(obj1,obj2)

def task(arg):
  obj = Singleton()
  print(obj)

for i in range(10):
  t = threading.Thread(target=task,args=[i,])
  t.start()

    d、基于metaclass方式实现单例模式

"""
1.对象是类创建,创建对象时候类的__init__方法自动执行,对象()执行类的 __call__ 方法
2.类是type创建,创建类时候type的__init__方法自动执行,类() 执行type的 __call__方法(类的__new__方法,类的__init__方法)

# 第0步: 执行type的 __init__ 方法【类是type的对象】
class Foo:
  def __init__(self):
    pass

  def __call__(self, *args, **kwargs):
    pass

# 第1步: 执行type的 __call__ 方法
#    1.1 调用 Foo类(是type的对象)的 __new__方法,用于创建对象。
#    1.2 调用 Foo类(是type的对象)的 __init__方法,用于对对象初始化。
obj = Foo()
# 第2步:执行Foodef __call__ 方法
obj()
"""

import threading

class SingletonType(type):
  _instace_lock=threading.Lock()
  def __call__(cls, *args, **kwargs):
    if not hasattr(cls, "_instance"):
      with SingletonType._instace_lock:
        if not hasattr(cls, "_instance"):
          cls._instance = super(SingletonType,cls).__call__(*args, **kwargs)
    return cls._instance
class Foo(metaclass=SingletonType):
  def __init__(self,name):
    self.name=name


obj1 = Foo('name')
obj2 = Foo('name')
print(obj1,obj2)
Python 相关文章推荐
Python 第一步 hello world
Sep 25 Python
对于Python异常处理慎用“except:pass”建议
Apr 02 Python
python计算圆周率pi的方法
Jul 11 Python
利用Python破解斗地主残局详解
Jun 30 Python
Python中函数及默认参数的定义与调用操作实例分析
Jul 25 Python
python logging日志模块的详解
Oct 29 Python
python快速排序的实现及运行时间比较
Nov 22 Python
torch 中各种图像格式转换的实现方法
Dec 26 Python
Python实现FLV视频拼接功能
Jan 21 Python
Python中私有属性的定义方式
Mar 05 Python
Python 实现一个简单的web服务器
Jan 03 Python
解决Python import .pyd 可能遇到路径的问题
Mar 04 Python
ubuntu安装mysql pycharm sublime
Feb 20 #Python
python中(str,list,tuple)基础知识汇总
Feb 20 #Python
Python 反转字符串(reverse)的方法小结
Feb 20 #Python
python如何实现int函数的方法示例
Feb 19 #Python
Python cookbook(数据结构与算法)实现查找两个字典相同点的方法
Feb 18 #Python
Python cookbook(数据结构与算法)字典相关计算问题示例
Feb 18 #Python
Python cookbook(数据结构与算法)让字典保持有序的方法
Feb 18 #Python
You might like
利用PHP实现图片等比例放大和缩小的方法详解
2013/06/06 PHP
php设计模式之观察者模式实例详解【星际争霸游戏案例】
2020/03/30 PHP
node.js 一个简单的页面输出实现代码
2012/03/07 Javascript
JavaScript调用堆栈及setTimeout使用方法深入剖析
2013/02/16 Javascript
jQuery实现图片放大预览实现原理及代码
2013/09/12 Javascript
JavaScript设计模式之外观模式实例
2014/10/10 Javascript
Bootstrap安装环境配置教程分享
2016/05/27 Javascript
深入解析桶排序算法及Node.js上JavaScript的代码实现
2016/07/06 Javascript
jquery ui sortable拖拽后保存位置
2017/04/27 jQuery
JavaScript箭头函数_动力节点Java学院整理
2017/06/28 Javascript
bootstrap精简教程_动力节点Java学院整理
2017/07/14 Javascript
react-router4 嵌套路由的使用方法
2017/07/24 Javascript
基于wordpress的ajax写法详解
2018/01/02 Javascript
vue二级菜单导航点击选中事件的方法
2018/09/12 Javascript
详解Express笔记之动态渲染HTML(新手入坑)
2018/12/13 Javascript
深入解析koa之异步回调处理
2019/06/17 Javascript
openlayers4实现点动态扩散
2020/08/17 Javascript
JS轮播图的实现方法2
2020/08/25 Javascript
在Django的模型中执行原始SQL查询的方法
2015/07/21 Python
Python图算法实例分析
2016/08/13 Python
Python模拟登陆实现代码
2017/06/14 Python
Python网络编程使用select实现socket全双工异步通信功能示例
2018/04/09 Python
基于python OpenCV实现动态人脸检测
2018/05/25 Python
python使用adbapi实现MySQL数据库的异步存储
2019/03/19 Python
pyqt5数据库使用详细教程(打包解决方案)
2020/03/25 Python
为什么python比较流行
2020/06/19 Python
Python根据URL地址下载文件并保存至对应目录的实现
2020/11/15 Python
python+playwright微软自动化工具的使用
2021/02/02 Python
html5中监听canvas内部元素点击事件的三种方法
2019/04/28 HTML / CSS
玩具反斗城葡萄牙官方商城:Toys"R"Us葡萄牙
2016/10/21 全球购物
Steve Madden官网:美国鞋类品牌
2017/01/29 全球购物
电大毕业生自我鉴定
2014/04/10 职场文书
护士实习求职信
2014/06/22 职场文书
西双版纳导游词
2015/02/03 职场文书
Nginx服务器添加Systemd自定义服务过程解析
2021/03/31 Servers
浅谈pytorch中的dropout的概率p
2021/05/27 Python