Python單例模式實例分析

字號:


    本文實例講述了Python單例模式的使用方法。分享給大家供大家參考。具體如下:
    方法一
    復制代碼 代碼如下: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
    復制代碼 代碼如下:#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
    也應該加上線程安全
    復制代碼 代碼如下: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è)計有所幫助。