本文實(shí)例講述了Python單體模式的幾種常見(jiàn)實(shí)現(xiàn)方法。分享給大家供大家參考,具體如下:
這里python實(shí)現(xiàn)的單體模式,參考了:https://stackoverflow.com/questions/1363839/python-singleton-object-instantiation/1363852#1363852
一、修改父類(lèi)的 __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)注意,這種方法實(shí)現(xiàn)的并非真正的單體模式!!
下面幾種方法實(shí)現(xiàn)的才是真正的單體模式
二、使用元類(lèi)
先看看這里關(guān)于元類(lèi)的描述:
元類(lèi)一般用于創(chuàng)建類(lèi)。
在執(zhí)行類(lèi)定義時(shí),解釋器必須要知道這個(gè)類(lèi)的正確的元類(lèi)。解釋器會(huì)先尋找類(lèi)屬性__metaclass__,如果此屬性存在,就將這個(gè)屬性賦值給此類(lèi)作為它的元類(lèi)。如果此屬性沒(méi)有定義,它會(huì)向上查找父類(lèi)中的__metaclass__。如果還沒(méi)有發(fā)現(xiàn)__metaclass__屬性,解釋器會(huì)檢查名字為__metaclass__的全局變量,如果它存在,就使用它作為元類(lèi)。否則, 使用內(nèi)置的 type 作為此類(lèi)的元類(lèi)。
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())
下面還有一個(gè)很巧妙的方法實(shí)現(xiàn)單體模式
使用類(lèi)方法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
更多關(guān)于Python相關(guān)內(nèi)容可查看本站專(zhuān)題:《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python Socket編程技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門(mén)與進(jìn)階經(jīng)典教程》
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選