python实现单例模式的三种方法
單例模式
單例模式(Singleton Pattern)是一種常用的軟件設(shè)計模式,該模式的主要目的是確保某一個類只有一個實(shí)例存在。當(dāng)在整個系統(tǒng)中,某個類只能出現(xiàn)一個實(shí)例時,單例對象就能派上用場。
其目的就是令到單個進(jìn)程中只存在一個類的實(shí)例,從而可以實(shí)現(xiàn)數(shù)據(jù)的共享,節(jié)省系統(tǒng)開銷,防止io阻塞等等
比如,某個服務(wù)器程序的配置信息存放在一個文件中,客戶端通過一個 AppConfig 的類來讀取配置文件的信息。如果在程序運(yùn)行期間,有很多地方都需要使用配置文件的內(nèi)容,也就是說,很多地方都需要創(chuàng)建 AppConfig 對象的實(shí)例,這就導(dǎo)致系統(tǒng)中存在多個 AppConfig 的實(shí)例對象,而這樣會嚴(yán)重浪費(fèi)內(nèi)存資源,尤其是在配置文件內(nèi)容很多的情況下。事實(shí)上,類似 AppConfig 這樣的類,我們希望在程序運(yùn)行期間只存在一個實(shí)例對象。
實(shí)現(xiàn)的三種方法:
方法1:
使用基類 New 是真正創(chuàng)建實(shí)例對象的方法,所以重寫基類的new 方法,以此保證創(chuàng)建對象的時候只生成一個實(shí)例
方法2:使用裝飾器
def singleton(cls):instances = {}def wrapper(*args, **kwargs):if cls not in instances:instances[cls] = cls(*args, **kwargs)return instances[cls]return wrapper@singleton class Foo(object):passfoo1 = Foo() foo2 = Foo() print(foo1 is foo2) # True方法3:元類,元類是用于創(chuàng)建類對象的類,類對象創(chuàng)建實(shí)例對象時一定要調(diào)用call方法,因此在調(diào)用call時候保證始終只創(chuàng)建一個實(shí)例即可,type是python的元類.
class Singleton(type):def __call__(cls, *args, **kwargs):if not hasattr(cls, '_instance'):cls._instance = super(Singleton, cls).__call__(*args, **kwargs)return cls._instanceclass Foo(metaclass=Singleton):passfoo1 = Foo() foo2 = Foo() print(foo1 is foo2) # True學(xué)習(xí)整理轉(zhuǎn)載自:https://github.com/kenwoodjw/python_interview_question#
總結(jié)
以上是生活随笔為你收集整理的python实现单例模式的三种方法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python实现遍历目录与子目录,并找到
- 下一篇: Python中变量的作用域?(变量查找顺