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ì)本站的支持!
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

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