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

首頁 > 編程 > Python > 正文

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

2019-11-25 15:56:06
字體:
來源:轉載
供稿:網友

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單例模式的實例詳解,如有疑問請留言或者到本站的社區交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 东兴市| 睢宁县| 西昌市| 桓台县| 台湾省| 克什克腾旗| 昌图县| 怀来县| 元江| 奉新县| 台东县| 英山县| 荣昌县| 本溪| 陕西省| 丹棱县| 化州市| 琼海市| 西华县| 临沂市| 镇江市| 长海县| 沙河市| 云南省| 云浮市| 长海县| 湘潭市| 左云县| 余姚市| 米林县| 荃湾区| 兰州市| 肃北| 纳雍县| 于田县| 新巴尔虎左旗| 新干县| 油尖旺区| 岳阳县| 原平市| 陆河县|