国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python中單例模式總結(jié)

2020-02-22 23:15:43
字體:
供稿:網(wǎng)友

一、單例模式

    a、單例模式分為四種:文件,類,基于__new__方法實現(xiàn)單例模式,基于metaclass方式實現(xiàn)

    b、類實現(xiàn)如下:

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._instanceimport threadingdaf task(arg):  obj=Sigletion.instance()  print(obj)for i in range(10):  t=threading.Thread(target=task,args=[i,])  t.start()

    c、基于__new__方法實現(xiàn)單例模式

import timeimport threadingclass 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._instanceobj1=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方式實現(xiàn)單例模式

"""
1.對象是類創(chuàng)建,創(chuàng)建對象時候類的__init__方法自動執(zhí)行,對象()執(zhí)行類的 __call__ 方法
2.類是type創(chuàng)建,創(chuàng)建類時候type的__init__方法自動執(zhí)行,類() 執(zhí)行type的 __call__方法(類的__new__方法,類的__init__方法)

# 第0步: 執(zhí)行type的 __init__ 方法【類是type的對象】class Foo:  def __init__(self):    pass  def __call__(self, *args, **kwargs):    pass# 第1步: 執(zhí)行type的 __call__ 方法#    1.1 調(diào)用 Foo類(是type的對象)的 __new__方法,用于創(chuàng)建對象。#    1.2 調(diào)用 Foo類(是type的對象)的 __init__方法,用于對對象初始化。obj = Foo()# 第2步:執(zhí)行Foodef __call__ 方法obj()"""import threadingclass 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._instanceclass Foo(metaclass=SingletonType):  def __init__(self,name):    self.name=nameobj1 = Foo('name')obj2 = Foo('name')print(obj1,obj2)

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 汉源县| 兴国县| 金坛市| 清镇市| 朔州市| 驻马店市| 香格里拉县| 高州市| 天津市| 涡阳县| 新乡市| 龙泉市| 济宁市| 贵港市| 玉林市| 中卫市| 新乡县| 精河县| 玉环县| 孟州市| 龙陵县| 开鲁县| 民县| 米林县| 崇礼县| 盖州市| 芜湖市| 铜山县| 行唐县| 城市| 额敏县| 靖西县| 神池县| 寻乌县| 博客| 岳阳县| 育儿| 旅游| 杭锦旗| 蓝山县| 东乡族自治县|