Halo
发布于 2024-10-29 / 44 阅读 / 0 评论 / 0 点赞

单列模式

  1. 使用模块
  • myclass.py
class myclass( ):
    def fun(self):
       pass
instance = myclass()
  • call.py
import myclass
a = myclass.instance
  1. __new__
  • myclass.py
    __new__() 函数只能用于从object继承的新式类
    发现实例化对象的时候,调用__init__()初始化之前,先调用了__new__()方法
    __new__()必须要有返回值,返回实例化出来的实例,需要注意的是,可以return父类__new__()出来的实例,也可以直接将object的__new__()出来的实例返回
import threading
class myclass(object):
    _instance_lock = threading.Lock()

    def __init__(self):
       pass
       
    def __new__(cls, *args, **kwargs):
       with myclass._instance_lock:
           if not hasattr(myclass, "_instance"):
              myclass._instance = object.__new__(cls)  
       return myclass._instance
  • call.py
from myclass import myclass
obj1 = myclass()
obj2 = myclass()
print(obj1,obj2)

def task(arg):
    obj = myclass()
    print(obj)

for i in range(10):
    t = threading.Thread(target=task,args=[i,])
    t.start()
  1. __call__(metaclass方式)
  • myclass.py
    1.类由type创建,创建类时,type的__init__方法自动执行,类() 执行type的 __call__方法(类的__new__方法,类的__init__方法)
    2.对象由类创建,创建对象时,类的__init__方法自动执行,对象()执行类的 __call__ 方法
import threading

class myclass_template(type):
    _instance_lock = threading.Lock()
    
    def __call__(cls, *args, **kwargs):
       with myclass_template._instance_lock:
           if not hasattr(cls, "_instance"):
              cls._instance = super(myclass_template,cls).__call__(*args, **kwargs)
       return cls._instance

class myclass(metaclass=myclass_template):
    def __init__(self):
       pass


obj1 = myclass()
obj2 = myclass()
print(obj1,obj2)

评论