Python中单例模式总结

yipeiwu_com5年前Python基础

一、单例模式

    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)

相关文章

OpenCV实现人脸识别

主要有以下步骤: 1、人脸检测 2、人脸预处理 3、从收集的人脸训练机器学习算法 4、人脸识别 5、收尾工作 人脸检测算法: 基于Haar的脸部检测器的基本思想是,对于面部正面大部分区域...

Python md5与sha1加密算法用法分析

本文实例讲述了Python md5与sha1加密算法。分享给大家供大家参考,具体如下: MD5 MD5的全称是Message-Digest Algorithm 5(信息-摘要算法),在9...

Python使用pymysql小技巧

在使用pymysql的时候,通过fetchall()或fetchone()可以获得查询结果,但这个返回数据是不包含字段信息的(不如php方便)。查阅pymysql源代码后,其实获取查询结...

Flask框架响应、调度方法和蓝图操作实例分析

本文实例讲述了Flask框架响应、调度方法和蓝图操作。分享给大家供大家参考,具体如下: 响应 像现在大部分的互联网应用用的数据传输格式都是JSON,当用户访问一个URL,我们如何通过Fl...

分析运行中的 Python 进程详细解析

在 Java 中打印当前线程的方法栈,可以用 kill -3 命令向 JVM 发送一个 OS 信号,JVM 捕捉以后会自动 dump 出来;当然,也可以直接使用 jstack 工具完成,...