單利模式及python實現方式,單利python實現

來源:互聯網
上載者:User

單利模式及python實現方式,單利python實現
 單例模式

單例模式(Singleton Pattern)是一種常用的軟體設計模式,該模式的主要目的是確保某一個類只有一個執行個體存在。當希望在整個系統中,某個類只能出現一個執行個體時,單例對象就能派上用場。

比如,某個伺服器程式的配置資訊存放在一個檔案中,用戶端通過一個 AppConfig 的類來讀取設定檔的資訊。如果在程式運行期間,有很多地方都需要使用設定檔的內容,也就是說,很多地方都需要建立 AppConfig 對象的執行個體,這就導致系統中存在多個 AppConfig 的執行個體對象,而這樣會嚴重浪費記憶體資源,尤其是在設定檔內容很多的情況下。事實上,類似 AppConfig 這樣的類,我們希望在程式運行期間只存在一個執行個體對象

 

python實現單例模式使用模組實現

Python 的模組就是天然的單例模式,因為模組在第一次匯入時,會產生 .pyc 檔案,當第二次匯入時,就會直接載入 .pyc 檔案,而不會再次執行模組代碼。因此,我們只需把相關的函數和資料定義在一個模組中,就可以獲得一個單例對象了。

 mysingleton.py

class Singleton:    def foo(self):        print('foo')singleton=Singleton()

 

其他檔案

from mysingleton import singletonsingleton.foo()

 

 

裝飾器實現
def singleton(cls):    _instance = {}    def wraper(*args, **kargs):        if cls not in _instance:            _instance[cls] = cls(*args, **kargs)        return _instance[cls]    return wraper@singletonclass A(object):    def __init__(self, x=0):        self.x = xa1 = A(2)a2 = A(3)

最終執行個體化出一個對象並且儲存在_instance中,_instance的值也一定是

基於__new__方法實現

當我們執行個體化一個對象時,是先執行了類的__new__方法(我們沒寫時,預設調用object.__new__),執行個體化對象;然後再執行類的__init__方法,對這個對象進行初始化,所有我們可以基於這個,實現單例模式

class Singleton():    def __new__(cls, *args, **kwargs):        if not hasattr(cls,'_instance'):            cls._instance=object.__new__(cls)        return cls._instanceclass A(Singleton):    def __init__(self,x):        self.x=xa=A('han')b=A('tao')print(a.x)print(b.x)

 

為了保證安全執行緒需要在內部加入鎖

import threadingclass Singleton():    lock=threading.Lock    def __new__(cls, *args, **kwargs):        if not hasattr(cls,'_instance'):            with cls.lock:                if not hasattr(cls, '_instance'):                    cls._instance=object.__new__(cls)        return cls._instanceclass A(Singleton):    def __init__(self,x):        self.x=xa=A('han')b=A('tao')print(a.x)print(b.x)
 兩大注意: 1. 除了模組單例外,其他幾種模式的本質都是通過設定中間變數,來判斷類是否已經被執行個體。中間變數的訪問和更改存線上程安全的問題:在開啟多線程模式的時候需要加鎖處理。 2. __new__方法無法避免觸發__init__(),初始的成員變數會進行覆蓋。其他方法不會。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.