国产探花免费观看_亚洲丰满少妇自慰呻吟_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ā)表
主站蜘蛛池模板: 施甸县| 含山县| 台中市| 丰宁| 宿州市| 浙江省| 兴业县| 威远县| 佛教| 开封县| 泾源县| 洞口县| 庄河市| 灵川县| 奉化市| 潼关县| 乌兰浩特市| 噶尔县| 游戏| 邹城市| 乌鲁木齐县| 宜宾市| 崇阳县| 应城市| 佳木斯市| 工布江达县| 赤水市| 资兴市| 桃江县| 西贡区| 沂水县| 温宿县| 建宁县| 和硕县| 罗定市| 中宁县| 渝中区| 珠海市| 湖北省| 成都市| 连南|