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

首頁 > 編程 > Python > 正文

常見的在Python中實現(xiàn)單例模式的三種方法

2020-02-23 00:38:12
字體:
供稿:網(wǎng)友

單例模式是一種常用的軟件設(shè)計模式。在它的核心結(jié)構(gòu)中只包含一個被稱為單例類的特殊類。通過單例模式可以保證系統(tǒng)中一個類只有一個實例而且該實例易于外界訪問,從而方便對實例個數(shù)的控制并節(jié)約系統(tǒng)資源。如果希望在系統(tǒng)中某個類的對象只能存在一個,單例模式是最好的解決方案。

單例模式的要點有三個;一是某個類只能有一個實例;二是它必須自行創(chuàng)建這個實例;三是它必須自行向整個系統(tǒng)提供這個實例。在Python中,單例模式有以下幾種實現(xiàn)方式。

方法一、實現(xiàn)__new__方法,然后將類的一個實例綁定到類變量_instance上;如果cls._instance為None,則說明該類還沒有被實例化過,new一個該類的實例,并返回;如果cls._instance不為None,直接返回_instance,代碼如下:

class Singleton(object):   def __new__(cls, *args, **kwargs):    if not hasattr(cls, '_instance'):      orig = super(Singleton, cls)      cls._instance = orig.__new__(cls, *args, **kwargs)    return cls._instance class MyClass(Singleton):  a = 1 one = MyClass()two = MyClass() #one和two完全相同,可以用id(), ==, is檢測print id(one)  # 29097904print id(two)  # 29097904print one == two  # Trueprint one is two  # True

方法二、本質(zhì)上是方法一的升級版,使用__metaclass__(元類)的高級python用法,具體代碼如下:

class Singleton2(type):   def __init__(cls, name, bases, dict):    super(Singleton2, cls).__init__(name, bases, dict)    cls._instance = None   def __call__(cls, *args, **kwargs):    if cls._instance is None:      cls._instance = super(Singleton2, cls).__call__(*args, **kwargs)    return cls._instance class MyClass2(object):  __metaclass__ = Singleton2  a = 1 one = MyClass2()two = MyClass2() print id(one)  # 31495472print id(two)  # 31495472print one == two  # Trueprint one is two  # True


方法三、使用Python的裝飾器(decorator)實現(xiàn)單例模式,這是一種更Pythonic的方法;單利類本身的代碼不是單例的,通裝飾器使其單例化,代碼如下:

def singleton(cls, *args, **kwargs):  instances = {}  def _singleton():    if cls not in instances:      instances[cls] = cls(*args, **kwargs)    return instances[cls]  return _singleton @singletonclass MyClass3(object):  a = 1 one = MyClass3()two = MyClass3() print id(one)  # 29660784print id(two)  # 29660784print one == two  # Trueprint one is two  # True

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 横峰县| 遂川县| 交口县| 兰西县| 监利县| 河北省| 鄂州市| 天峨县| 衡水市| 左贡县| 阳山县| 祁东县| 东城区| 开鲁县| 金沙县| 扶风县| 礼泉县| 上犹县| 顺昌县| 铅山县| 临沧市| 商河县| 梓潼县| 无为县| 兰溪市| 安康市| 花莲市| 嵊州市| 闵行区| 民权县| 禄丰县| 麻阳| 丰顺县| 弥渡县| 顺昌县| 合水县| 马鞍山市| 宁陕县| 内丘县| 青州市| 潮州市|