知行编程网知行编程网  2022-12-02 14:30 知行编程网 隐藏边栏  0 
文章评分 0 次,平均分 0.0
导语: 本文主要介绍了关于python单例模式是什么意思的相关知识,希望可以帮到处于编程学习途中的小伙伴

python单例模式是什么意思

单例模式(Singleton Pattern)是一种常用的软件设计模式。这种模式的主要目的是确保某个类只存在一个实例。当你只想在整个系统中出现一个类的一个实例时,单例对象会派上用场。


单例模式


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__方法,object()执行类的__call__方法。

2.类是按类型创建的。创建类时,会自动执行type的__init__方法,class()会执行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)

本文为原创文章,版权归所有,欢迎分享本文,转载请保留出处!

知行编程网
知行编程网 关注:1    粉丝:1
这个人很懒,什么都没写
扫一扫二维码分享