国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python單例模式實例分析

2020-02-23 06:19:55
字體:
來源:轉載
供稿:網友

本文實例講述了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__方法,不能直接創建對象。

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

3.@staticmethod,靜態方法,通過類名直接調用。

4.__lock,代碼鎖。

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

6.雙重檢查加鎖,既可實現線程安全,又使性能不受很大影響。

方法二:使用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 
 

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 荔浦县| 乌拉特中旗| 循化| 资中县| 子长县| 长泰县| 武乡县| 井陉县| 镇宁| 蚌埠市| 丰镇市| 思南县| 通海县| 吴桥县| 迭部县| 墨竹工卡县| 永胜县| 镇平县| 靖西县| 巩留县| 普宁市| 泰宁县| 隆林| 宁明县| 佛学| 扶绥县| 贡嘎县| 平塘县| 万年县| 错那县| 北京市| 郴州市| 松溪县| 泸州市| 宿迁市| 松阳县| 札达县| 迭部县| 新建县| 襄汾县| 星子县|