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)

相关文章

AI人工智能 Python实现人机对话

AI人工智能 Python实现人机对话

在人工智能进展的如火如荼的今天,我们如果不尝试去接触新鲜事物,马上就要被世界淘汰啦~ 本文拟使用Python开发语言实现类似于WIndows平台的“小娜”,或者是IOS下的“Siri”。...

Python 类,property属性(简化属性的操作),@property,property()用法示例

本文实例讲述了Python 类,property属性(简化属性的操作),@property,property()用法。分享给大家供大家参考,具体如下: property属性的创建方式有两...

Python内置函数dir详解

1.命令介绍 最近学习并使用了一个python的内置函数dir,首先help一下: 复制代码 代码如下: >>> help(dir) Help on built-in...

扩展Django admin的list_filter()可使用范围方法

扩展Django admin的list_filter()可使用范围方法

需求描述 有时候我们会基于已有数据生成一列在表格中,类似于下面的 class BaseSchema(models.Model): ... def test_status(self...

Python绘制股票移动均线的实例

Python绘制股票移动均线的实例

1. 前沿 移动均线是股票最进本的指标,本文采用numpy.convolve计算股票的移动均线 2. numpy.convolve numpy.convolve(a, v, mode='...