Python單例模式實(shí)例分析
本文實(shí)例講述了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)建對(duì)象。
2.__instance,單例對(duì)象私有化。
3.@staticmethod,靜態(tài)方法,通過(guò)類名直接調(diào)用。
4.__lock,代碼鎖。
5.繼承object類,通過(guò)調(diào)用object的__new__方法創(chuàng)建單例對(duì)象,然后調(diào)用object的__init__方法完整初始化。
6.雙重檢查加鎖,既可實(shí)現(xiàn)線程安全,又使性能不受很大影響。
方法二:使用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
也應(yīng)該加上線程安全
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
希望本文所述對(duì)大家的Python程序設(shè)計(jì)有所幫助。
相關(guān)文章
Python保留數(shù)據(jù)并刪除Excel單元格的函數(shù)和公式
在分析處理Excel表格時(shí),我們可能需要使用各種公式或函數(shù)對(duì)表格數(shù)據(jù)進(jìn)行計(jì)算,從而分析出更多的信息,但在展示、分享或再利用分析結(jié)果時(shí),我們可能需要將含有公式的單元格轉(zhuǎn)換為靜態(tài)數(shù)值,本文將介紹如何使用Python代碼批量移除Excel單元格中的公式并保留數(shù)值2024-10-10
Python簡(jiǎn)單實(shí)現(xiàn)兩個(gè)任意字符串乘積的方法示例
這篇文章主要介紹了Python簡(jiǎn)單實(shí)現(xiàn)兩個(gè)任意字符串乘積的方法,結(jié)合實(shí)例形式分析了Python針對(duì)字符串、列表的切片、轉(zhuǎn)換、遍歷等相關(guān)操作技巧,需要的朋友可以參考下2018-04-04

