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單例模式的實例詳解,如有疑問請留言或者到本站的社區交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
