飄逸的python - 單例模式亂彈

來源:互聯網
上載者:User

標籤:python   裝飾器   單例模式   設計模式   

方法一:裝飾器

利用“裝飾器只會執行一次”這個特點

def singleton(cls):    instances = []# 為什麼這裡不直接為None,因為內建函式沒法訪問外部函數的非容器變數    def getinstance(*args, **kwargs):        if not instances:            instances.append(cls(*args, **kwargs))        return instances[0]    return getinstance@singletonclass Foo:    a = 1f1 = Foo()f2 = Foo()print id(f1), id(f2)
方法二:基類

利用“類變數對所有對象唯一”,即cls._instance

class Singleton(object):    def __new__(cls, *args, **kwargs):        if not hasattr(cls, ‘_instance‘):            cls._instance = object.__new__(cls, *args, **kwargs)        return cls._instanceclass Foo(Singleton):    a = 1
方法三:metaclass

利用“類變數對所有對象唯一”,即cls._instance

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
方法四:Borg模式

利用“類變數對所有對象唯一”,即__share_state

class Foo:   __share_state = {}   def __init__(self):       self.__dict__ = self.__share_state
方法五:利用import

利用“模組只會被import一次”

#在檔案mysingleton中class Foo(object):     passf = Foo()

然後在其它模組,from mysingleton import f
直接拿f當作單例的對象來用

飄逸的python - 單例模式亂彈

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.