本文實(shí)例講述了Python單例模式的使用方法。分享給大家供大家參考。具體如下:
方法一
復(fù)制代碼 代碼如下: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ì)象私有化。
靜態(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
復(fù)制代碼 代碼如下:#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)該加上線程安全
復(fù)制代碼 代碼如下: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
希望本文所述對(duì)大家的Python程序設(shè)計(jì)有所幫助。
更多信息請(qǐng)查看IT技術(shù)專欄