Python中单例模式总结

yipeiwu_com6年前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)

相关文章

python3中property使用方法详解

本文实例为大家分享了python3中的property使用方法,供大家参考,具体内容如下 property属性 定义 一个可以使实例方法用起来像实例属性一样的特殊关键字,可以对应于某个方...

pytorch 归一化与反归一化实例

ToTensor中就有转到0-1之间了。 # -*- coding:utf-8 -*- import time import torch from torchvisi...

python计算圆周率pi的方法

本文实例讲述了python计算圆周率pi的方法。分享给大家供大家参考。具体如下: from sys import stdout scale = 10000 maxarr = 28...

python 浅谈serial与stm32通信的编码问题

参考链接: decode错误处理方案 可选用的编码 使用环境: ubuntu18.04 python3.65 问题点: 使用pyserial与stm32通信,使用如下形式的编码进行wri...

Python科学计算之NumPy入门教程

前言 NumPy是Python用于处理大型矩阵的一个速度极快的数学库。它允许你在Python中做向量和矩阵的运算,而且很多底层的函数都是用C写的,你将获得在普通Python中无法达到的...