午夜国产狂喷潮在线观看|国产AⅤ精品一区二区久久|中文字幕AV中文字幕|国产看片高清在线

    Python單例模式實例分析
    來源:易賢網(wǎng) 閱讀:748 次 日期:2015-01-16 14:45:21
    溫馨提示:易賢網(wǎng)小編為您整理了“Python單例模式實例分析”,方便廣大網(wǎng)友查閱!

    本文實例講述了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)建對象。

    2.__instance,單例對象私有化。

    靜態(tài)方法,通過類名直接調(diào)用。

    4.__lock,代碼鎖。

    5.繼承object類,通過調(diào)用object的__new__方法創(chuàng)建單例對象,然后調(diào)用object的__init__方法完整初始化。

    6.雙重檢查加鎖,既可實現(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

    希望本文所述對大家的Python程序設(shè)計有所幫助。

    更多信息請查看IT技術(shù)專欄

    更多信息請查看腳本欄目
    易賢網(wǎng)手機網(wǎng)站地址:Python單例模式實例分析
    由于各方面情況的不斷調(diào)整與變化,易賢網(wǎng)提供的所有考試信息和咨詢回復(fù)僅供參考,敬請考生以權(quán)威部門公布的正式信息和咨詢?yōu)闇?zhǔn)!

    2025國考·省考課程試聽報名

    • 報班類型
    • 姓名
    • 手機號
    • 驗證碼
    關(guān)于我們 | 聯(lián)系我們 | 人才招聘 | 網(wǎng)站聲明 | 網(wǎng)站幫助 | 非正式的簡要咨詢 | 簡要咨詢須知 | 新媒體/短視頻平臺 | 手機站點 | 投訴建議
    工業(yè)和信息化部備案號:滇ICP備2023014141號-1 云南省教育廳備案號:云教ICP備0901021 滇公網(wǎng)安備53010202001879號 人力資源服務(wù)許可證:(云)人服證字(2023)第0102001523號
    云南網(wǎng)警備案專用圖標(biāo)
    聯(lián)系電話:0871-65099533/13759567129 獲取招聘考試信息及咨詢關(guān)注公眾號:hfpxwx
    咨詢QQ:1093837350(9:00—18:00)版權(quán)所有:易賢網(wǎng)
    云南網(wǎng)警報警專用圖標(biāo)