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实现的一个火车票转让信息采集器
Jul 09 Python
用Python编写一个简单的Lisp解释器的教程
Apr 03 Python
Python工程师面试题 与Python Web相关
Jan 14 Python
利用python发送和接收邮件
Sep 27 Python
Python实现Linux中的du命令
Jun 12 Python
Python 比较文本相似性的方法(difflib,Levenshtein)
Oct 15 Python
连接pandas以及数组转pandas的方法
Jun 28 Python
3行Python代码实现图像照片抠图和换底色的方法
Oct 10 Python
Python上下文管理器全实例详解
Nov 12 Python
多个python文件调用logging模块报错误
Feb 12 Python
django实现日志按日期分割
May 21 Python
教你如何使用Python下载B站视频的详细教程
Apr 29 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
曾在DC漫画界反派角色扮演的演员,谁才是你心目中的小丑之王?
2020/04/09 欧美动漫
Ajax PHP 边学边练 之三 数据库
2009/11/26 PHP
基于php缓存的详解
2013/05/15 PHP
使用php语句将数据库*.sql文件导入数据库
2014/05/05 PHP
php生成html文件方法总结
2014/12/01 PHP
thinkphp 手机号和用户名同时登录
2017/01/20 PHP
jQuery动态添加删除select项(实现代码)
2013/09/03 Javascript
javascript 回到顶部效果的实现代码
2014/02/17 Javascript
JS组件Bootstrap按钮组与下拉按钮详解
2016/05/10 Javascript
jQuery 检查某个元素在页面上是否存在实例代码
2016/10/27 Javascript
JS限制条件补全问题实例分析
2016/12/16 Javascript
原生Aajax 和jQuery Ajax 写法个人总结
2017/03/24 jQuery
Javascript(es2016) import和require用法和区别详解
2017/08/11 Javascript
前端必备插件之纯原生JS的瀑布流插件Macy.js
2017/11/22 Javascript
jQuery实现模拟搜索引擎的智能提示功能简单示例
2019/01/27 jQuery
paramiko模块安装和使用(远程登录服务器)
2014/01/27 Python
python多线程编程中的join函数使用心得
2014/09/02 Python
简单的Python的curses库使用教程
2015/04/11 Python
对python使用telnet实现弱密码登录的方法详解
2019/01/26 Python
pyqt5 禁止窗口最大化和禁止窗口拉伸的方法
2019/06/18 Python
PyQt5多线程刷新界面防假死示例
2019/12/13 Python
打印机墨盒:123Inkjets
2017/02/16 全球购物
New Balance美国官网:运动鞋和健身服装
2017/04/11 全球购物
牵手50香港:专为黄金岁月的单身人士而设的交友网站
2020/08/14 全球购物
某/etc/fstab文件中的某行如下: /dev/had5 /mnt/dosdata msdos defaults,usrquota 1 2 请解释其含义
2013/04/11 面试题
一些关于MySql加速和优化的面试题
2014/01/30 面试题
J2EE的优越性主要表现在哪些方面
2016/03/28 面试题
建筑公司文秘岗位职责
2013/11/29 职场文书
职工运动会邀请函
2014/01/19 职场文书
最美乡村医生事迹材料
2014/06/02 职场文书
网站出售协议书范文
2014/10/10 职场文书
2014年村计划生育工作总结
2014/11/14 职场文书
2015年话务员工作总结
2015/04/29 职场文书
护士业务学习心得体会
2016/01/25 职场文书
python+opencv实现视频抽帧示例代码
2021/06/11 Python
Python初学者必备的文件读写指南
2021/06/23 Python