目錄
- 基本介紹
- 優(yōu)缺點(diǎn)
- Python實(shí)現(xiàn)
- 方式1,元類實(shí)現(xiàn):
- 方式2,繼承實(shí)現(xiàn):
- 方式3,裝飾器實(shí)現(xiàn):
- 方式4,模塊實(shí)現(xiàn):
- 方式5,@classmethod實(shí)現(xiàn)單例模式:
基本介紹
一個(gè)對(duì)象只允許被一次創(chuàng)建,一個(gè)類只能創(chuàng)建一個(gè)對(duì)象,并且提供一個(gè)全局訪問點(diǎn)。
單例模式應(yīng)該是應(yīng)用最廣泛,實(shí)現(xiàn)最簡單的一種創(chuàng)建型模式。
特點(diǎn):全局唯一,允許更改
優(yōu)缺點(diǎn)
優(yōu)點(diǎn):
- 避免對(duì)資源的多重占用,如寫入文件操作
- 節(jié)省內(nèi)存
- 防止命名空間被污染
缺點(diǎn):
- 沒有接口,不能繼承,與單一職責(zé)原則沖突,一個(gè)類應(yīng)該只關(guān)心內(nèi)部邏輯,而不關(guān)心外面怎么樣來實(shí)例化
Python實(shí)現(xiàn)
方式1,元類實(shí)現(xiàn):
class MetaClass(type):
def __call__(self, *args, **kwargs):
"""
self : class Singleton
"""
if not hasattr(self, "ins"):
insObject = super(__class__, self).__call__(*args, **kwargs)
setattr(self, "ins", insObject)
return getattr(self, "ins")
class Singleton(object, metaclass=MetaClass):
pass
if __name__ == "__main__":
ins = Singleton()
print(id(ins))
ins = Singleton()
print(id(ins))
方式2,繼承實(shí)現(xiàn):
class ParentClass:
def __new__(cls, *args, **kwargs) -> object:
"""
cls : class Singeton
"""
if not hasattr(cls, "ins"):
insObject = super(__class__, cls).__new__(cls, *args, **kwargs)
setattr(cls, "ins", insObject)
return getattr(cls, "ins")
class Singleton(ParentClass):
pass
if __name__ == "__main__":
ins = Singleton()
print(id(ins))
ins = Singleton()
print(id(ins))
方式3,裝飾器實(shí)現(xiàn):
def warpper(clsObject):
def inner(*args, **kwargs):
if not hasattr(clsObject, "ins"):
insObject = clsObject(*args, **kwargs)
setattr(clsObject, "ins", insObject)
return getattr(clsObject, "ins")
return inner
@warpper
class Singleton:
pass
if __name__ == "__main__":
ins = Singleton()
print(id(ins))
ins = Singleton()
print(id(ins))
方式4,模塊實(shí)現(xiàn):
- foo.py --> ins = Singleton()
- bar.py --> from foo import ins
方式5,@classmethod實(shí)現(xiàn)單例模式:
class Singleton:
@classmethod
def getSingletonInstanceObject(cls, *args, **kwargs):
if not hasattr(cls, "ins"):
insObject = cls(*args, **kwargs)
setattr(cls, "ins", insObject)
return getattr(cls, "ins")
if __name__ == "__main__":
ins = Singleton.getSingletonInstanceObject()
print(id(ins))
ins = Singleton.getSingletonInstanceObject()
print(id(ins))
到此這篇關(guān)于Python實(shí)現(xiàn)單例模式的5種方法的文章就介紹到這了,更多相關(guān)Python 單例模式內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- python 6種方法實(shí)現(xiàn)單例模式
- python 實(shí)現(xiàn)單例模式的5種方法
- python單例模式的多種實(shí)現(xiàn)方法
- 詳解python實(shí)現(xiàn)線程安全的單例模式
- 基于Python中單例模式的幾種實(shí)現(xiàn)方式及優(yōu)化詳解
- Python單例模式的兩種實(shí)現(xiàn)方法
- 5種Python單例模式的實(shí)現(xiàn)方式
- 常見的在Python中實(shí)現(xiàn)單例模式的三種方法