Python單例模式實例分析
本文實例講述了Python單例模式的使用方法。分享給大家供大家參考。具體如下:
方法一
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)建對象。
2.__instance,單例對象私有化。
3.@staticmethod,靜態(tài)方法,通過類名直接調用。
4.__lock,代碼鎖。
5.繼承object類,通過調用object的__new__方法創(chuàng)建單例對象,然后調用object的__init__方法完整初始化。
6.雙重檢查加鎖,既可實現線程安全,又使性能不受很大影響。
方法二:使用decorator
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
也應該加上線程安全
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程序設計有所幫助。
相關文章
Python光學仿真wxpython透鏡演示系統(tǒng)框架
這篇文章主要為大家介紹了Python光學仿真UI界面的wxpython透鏡演示系統(tǒng)框架基本講解,有需要的朋友可以借鑒參考下,希望能夠有所幫助2021-10-10Python標準庫之urllib和urllib3的使用及說明
這篇文章主要介紹了Python標準庫之urllib和urllib3使用及說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-12-12Python數據結構與算法之圖的廣度優(yōu)先與深度優(yōu)先搜索算法示例
這篇文章主要介紹了Python數據結構與算法之圖的廣度優(yōu)先與深度優(yōu)先搜索算法,結合實例形式分析了圖的廣度優(yōu)先與深度優(yōu)先搜索算法原理與相關實現技巧,需要的朋友可以參考下2017-12-12Windows安裝Anaconda并且配置國內鏡像的詳細教程
我們在學習 Python 的時候需要不同的 Python 版本,關系到電腦環(huán)境變量配置換來換去很是麻煩,所以這個時候我們需要一個虛擬的 Python 環(huán)境變量,這篇文章主要介紹了Windows安裝Anaconda并且配置國內鏡像教程,需要的朋友可以參考下2023-01-01