Singleton Pattern 是針對(duì)class的一種軟件設(shè)計(jì)模式部服,用以確保該class在系統(tǒng)的生命周期內(nèi)僅存在唯一一個(gè)實(shí)例。此文僅用于記錄本人所常選用的一種單例模式坟乾,更多單例模式的實(shí)現(xiàn)方法參考一下連接:
werediver/singleton.py
Python單例模式
Python中的單例模式的幾種實(shí)現(xiàn)方式的及優(yōu)化
設(shè)計(jì)模式(Python)-單例模式
import time
import threading
class Singleton(object):
_instance = None
_instance_lock = threading.Lock()
def __init__(self):
pass
@classmethod
def instance(cls):
with cls._instance_lock:
if not cls._instance:
cls._instance = cls()
return cls._instance
def task(arg):
obj = Singleton.instance()
print(obj)
for i in range(10):
t = threading.Thread(target=task,args=[i,])
t.start()
time.sleep(20)
obj = Singleton.instance()
print(obj)
其中
with some_lock:
# do something...
等同于
some_lock.acquire()
try:
# do something...
finally:
some_lock.release()