Python單例模式的兩種實(shí)現(xiàn)方法
Python單例模式的兩種實(shí)現(xiàn)方法
方法一
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__方法,不能直接創(chuàng)建對(duì)象。
2.__instance,單例對(duì)象私有化。
3.@staticmethod,靜態(tài)方法,通過類名直接調(diào)用。
4.__lock,代碼鎖。
5.繼承object類,通過調(diào)用object的__new__方法創(chuàng)建單例對(duì)象,然后調(diào)用object的__init__方法完整初始化。
6.雙重檢查加鎖,既可實(shí)現(xiàn)線程安全,又使性能不受很大影響。
方法二:使用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
也應(yīng)該加上線程安全
附:性能沒有方法一高
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單例模式的實(shí)例詳解,如有疑問請(qǐng)留言或者到本站的社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
相關(guān)文章
tensorflow 動(dòng)態(tài)獲取 BatchSzie 的大小實(shí)例
這篇文章主要介紹了tensorflow 動(dòng)態(tài)獲取 BatchSzie 的大小實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-06-06Python 3.10 的首個(gè) PEP 誕生,內(nèi)置類型 zip() 迎來新特性(推薦)
這篇文章主要介紹了Python 3.10 的首個(gè) PEP 誕生,內(nèi)置類型 zip() 迎來新特性,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-07-07Python?Excel操作從零學(xué)習(xí)掌握openpyxl用法
這篇文章主要為大家介紹了Python?Excel操作從零學(xué)習(xí)掌握openpyxl用法示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-08-08Python實(shí)現(xiàn)的合并兩個(gè)有序數(shù)組算法示例
這篇文章主要介紹了Python實(shí)現(xiàn)的合并兩個(gè)有序數(shù)組算法,涉及Python針對(duì)數(shù)組的遍歷、計(jì)算、追加等相關(guān)操作技巧,需要的朋友可以參考下2019-03-03關(guān)于Pyinstaller打包eel和pygame需要注意的坑
這篇文章主要介紹了關(guān)于Pyinstaller打包eel和pygame需要注意的坑,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-02-02