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

首頁 > 編程 > Python > 正文

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

2020-01-04 15:50:27
字體:
供稿:網(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)


注:相關(guān)教程知識閱讀請移步到python教程頻道。
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 民权县| 洛隆县| 汉寿县| 涞源县| 永和县| 措勤县| 田东县| 苍梧县| 克东县| 大新县| 刚察县| 芮城县| 雷州市| 鲁山县| 上饶县| 福贡县| 清镇市| 鄢陵县| 广灵县| 江源县| 临泽县| 太康县| 东光县| 宣威市| 辽阳县| 黄梅县| 汉中市| 墨竹工卡县| 论坛| 滨海县| 蓝山县| 苏尼特右旗| 北碚区| 晴隆县| 东源县| 清水河县| 江陵县| 喀什市| 微博| 锦州市| 锦州市|