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

首頁 > 編程 > Python > 正文

Python單例模式的兩種實現方法

2020-02-16 02:04:23
字體:
來源:轉載
供稿:網友

Python單例模式的兩種實現方法

方法一 

import threading  class Singleton(object):   __instance = None    __lock = threading.Lock()  # used to synchronize code    def __init__(self):     "disable the __init__ method"    @staticmethod   def getInstance():     if not Singleton.__instance:       Singleton.__lock.acquire()       if not Singleton.__instance:         Singleton.__instance = object.__new__(Singleton)         object.__init__(Singleton.__instance)       Singleton.__lock.release()     return Singleton.__instance 

 1.禁用__init__方法,不能直接創建對象。

 2.__instance,單例對象私有化。

 3.@staticmethod,靜態方法,通過類名直接調用。

 4.__lock,代碼鎖。

 5.繼承object類,通過調用object的__new__方法創建單例對象,然后調用object的__init__方法完整初始化。 

6.雙重檢查加鎖,既可實現線程安全,又使性能不受很大影響。 

方法二:使用decorator

#encoding=utf-8 def singleton(cls):   instances = {}   def getInstance():     if cls not in instances:       instances[cls] = cls()     return instances[cls]   return getInstance  @singleton class SingletonClass:   pass  if __name__ == '__main__':   s = SingletonClass()   s2 = SingletonClass()   print s   print s2  

也應該加上線程安全  

附:性能沒有方法一高

import threading  class Sing(object):   def __init__():     "disable the __init__ method"    __inst = None # make it so-called private    __lock = threading.Lock() # used to synchronize code    @staticmethod   def getInst():     Sing.__lock.acquire()     if not Sing.__inst:       Sing.__inst = object.__new__(Sing)       object.__init__(Sing.__inst)     Sing.__lock.release()     return Sing.__inst 

以上就是Python單例模式的實例詳解,如有疑問請留言或者到本站的社區交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 康定县| 东台市| 临泽县| 成都市| 饶平县| 砚山县| 安乡县| 永宁县| 蒙阴县| 德钦县| 陇西县| 白水县| 泸西县| 固镇县| 荆门市| 资讯 | 昭苏县| 大化| 贵阳市| 舟山市| 曲松县| 景宁| 当雄县| 志丹县| 中西区| 交口县| 铜山县| 张家界市| 武定县| 福建省| 商水县| 莱州市| 弋阳县| 古田县| 昌图县| 马公市| 沾化县| 合川市| 陕西省| 东兴市| 化州市|