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

首頁 > 學(xué)院 > 開發(fā)設(shè)計 > 正文

Python單例模式研究

2019-11-14 17:24:58
字體:
供稿:網(wǎng)友

方法一

 

Python代碼  收藏代碼
  1. import threading  
  2.   
  3. class Singleton(object):  
  4.     __instance = None  
  5.   
  6.     __lock = threading.Lock()   # used to synchronize code  
  7.   
  8.     def __init__(self):  
  9.         "disable the __init__ method"  
  10.  
  11.     @staticmethod  
  12.     def getInstance():  
  13.         if not Singleton.__instance:  
  14.             Singleton.__lock.acquire()  
  15.             if not Singleton.__instance:  
  16.                 Singleton.__instance = object.__new__(Singleton)  
  17.                 object.__init__(Singleton.__instance)  
  18.             Singleton.__lock.release()  
  19.         return Singleton.__instance  

 1.禁用__init__方法,不能直接創(chuàng)建對象。

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

 3.@staticmethod,靜態(tài)方法,通過類名直接調(diào)用。

 4.__lock,代碼鎖。

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

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

 

方法二:使用decorator

 

Python代碼  收藏代碼
  1. #encoding=utf-8  
  2. def singleton(cls):  
  3.     instances = {}  
  4.     def getInstance():  
  5.         if cls not in instances:  
  6.             instances[cls] = cls()  
  7.         return instances[cls]  
  8.     return getInstance  
  9.  
  10. @singleton  
  11. class SingletonClass:  
  12.     pass  
  13.   
  14. if __name__ == '__main__':  
  15.     s = SingletonClass()  
  16.     s2 = SingletonClass()  
  17.     PRint s  
  18.     print s2  

 

也應(yīng)該加上線程安全

 

 

附:性能沒有方法一高

 

Python代碼  收藏代碼
  1. import threading  
  2.   
  3. class Sing(object):  
  4.     def __init__():  
  5.         "disable the __init__ method"  
  6.   
  7.     __inst = None # make it so-called private  
  8.   
  9.     __lock = threading.Lock() # used to synchronize code  
  10.  
  11.     @staticmethod  
  12.     def getInst():  
  13.         Sing.__lock.acquire()  
  14.         if not Sing.__inst:  
  15.             Sing.__inst = object.__new__(Sing)  
  16.             object.__init__(Sing.__inst)  
  17.         Sing.__lock.release()  
  18.         return Sing.__inst  

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 富顺县| 宁夏| 沐川县| 宣汉县| 承德县| 平定县| 高邮市| 唐山市| 满洲里市| 洞口县| 六枝特区| 武乡县| 高平市| 绥德县| 嘉鱼县| 临泉县| 深州市| 拜城县| 荥阳市| 凤翔县| 门头沟区| 许昌市| 宣汉县| 蒲城县| 斗六市| 公安县| 五莲县| 崇州市| 萨嘎县| 石门县| 武宣县| 德庆县| 嘉鱼县| 板桥市| 临泉县| 宜昌市| 天全县| 通城县| 庆元县| 平泉县| 浪卡子县|