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

首頁 > 編程 > Python > 正文

Python單體模式的幾種常見實現(xiàn)方法詳解

2020-02-16 01:58:31
字體:
來源:轉載
供稿:網(wǎng)友

本文實例講述了Python單體模式的幾種常見實現(xiàn)方法。分享給大家供大家參考,具體如下:

這里python實現(xiàn)的單體模式,參考了:https://stackoverflow.com/questions/1363839/python-singleton-object-instantiation/1363852#1363852

一、修改父類的 __dict__

class Borg:  _shared_state = {}  def __init__(self):    self.__dict__ = self._shared_stateclass Singleton(Borg):  def __init__(self, name):    super().__init__()    self.name = name  def __str__(self):    return self.namex = Singleton('sausage')print(x)y = Singleton('eggs')print(y)z = Singleton('spam')print(z)print(x)print(y)

注意,這種方法實現(xiàn)的并非真正的單體模式!!

下面幾種方法實現(xiàn)的才是真正的單體模式

二、使用元類

先看看這里關于元類的描述:

元類一般用于創(chuàng)建類。

在執(zhí)行類定義時,解釋器必須要知道這個類的正確的元類。解釋器會先尋找類屬性__metaclass__,如果此屬性存在,就將這個屬性賦值給此類作為它的元類。如果此屬性沒有定義,它會向上查找父類中的__metaclass__。如果還沒有發(fā)現(xiàn)__metaclass__屬性,解釋器會檢查名字為__metaclass__的全局變量,如果它存在,就使用它作為元類。否則, 使用內(nèi)置的 type 作為此類的元類。

1. 繼承 type,使用 __call__

注意__call__的參數(shù)

class Singleton(type):  _instance = None  def __call__(self, *args, **kw):    if self._instance is None:      self._instance = super().__call__(*args, **kw)    return self._instanceclass MyClass(object):  __metaclass__ = Singletonprint(MyClass())print(MyClass())

2. 繼承 type,使用 __new__

注意__new__的參數(shù)

class Singleton(type):  _instance = None  def __new__(cls, name, bases, dct):    if cls._instance is None:      cls._instance = super().__new__(cls, name, bases, dct)    return cls._instanceclass MyClass(object):  __metaclass__ = Singletonprint(MyClass())print(MyClass())

3. 繼承 object,使用 __new__

注意__new__的參數(shù)

class Singleton(object):  _instance = None  def __new__(cls):    if cls._instance is None:      cls._instance = super().__new__(cls)    return cls._instanceclass MyClass(object):  __metaclass__ = Singletonprint(MyClass())print(MyClass())

下面還有一個很巧妙的方法實現(xiàn)單體模式

使用類方法classmethod

class Singleton:  _instance = None  @classmethod  def create(cls):    if cls._instance is None:      cls._instance = cls()    return cls._instance  def __init__(self):    self.x = 5    # or whatever you want to dosing = Singleton.create()print(sing.x) # 5sec = Singleton.create()print(sec.x) # 5            
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 祁连县| 自贡市| 墨江| 东兰县| 娱乐| 新兴县| 怀化市| 永靖县| 长垣县| 扬州市| 稷山县| 梅州市| 旬阳县| 克拉玛依市| 渭源县| 富锦市| 浠水县| 荆州市| 兴安盟| 津市市| 东丰县| 桓台县| 孙吴县| 永修县| 静乐县| 酒泉市| 伊宁市| 绍兴市| 定远县| 炎陵县| 宣威市| 湟中县| 永登县| 毕节市| 苍梧县| 庆云县| 古交市| 壤塘县| 隆回县| 云南省| 青龙|