Python實現單例模式

來源:互聯網
上載者:User

標籤:執行   strong   運行   let   san   code   python實現   應用   zhang   

單例模式1.什麼是單例?

確保某一個類只有一個執行個體,而且自行執行個體化並向整個系統提供這個執行個體,這個類稱為單例類,單例模式是一種對象建立型模式。
那麼單例模式有什麼用途呢?舉個常見的單例模式例子,我們平時使用的電腦上都有一個資源回收筒,在整個作業系統中,資源回收筒只能有一個執行個體,整個系統都使用這個唯一的執行個體,而且資源回收筒自行提供自己的執行個體,因此資源回收筒是單例模式的應用。

2.建立單例-保證只有1個對象
class Singleton(object):    __instance = None    def __new__(cls, name, age):        # 如果類屬性__instance的值為None,那麼就建立一個對象        if not cls.__instance:            cls.__instance = object.__new__(cls)        # 如果已經有執行個體存在,直接返回        return cls.__instancea = Singleton("Zhangsan", 18)b = Singleton("lisi", 20)print(id(a))print(id(b))a.age = 30   # 給a指向的對象添加一個屬性print(b.age)  # 擷取b指向的對象的age屬性

運行結果:

2946414454432294641445443230
3.建立單例,只執行1次 init方法
class Singleton(object):    __instance = None    __first_init = False    def __new__(cls, name, age):        if not cls.__instance:            cls.__instance = object.__new__(cls)        return cls.__instance    def __init__(self, name, age):        if not self.__first_init:            self.name = name            self.age = age            Singleton.__first_init = Truea = Singleton("Zhangsan", 18)b = Singleton("lisi", 20)print(id(a))print(id(b))print(a.name, a.age)print(b.name, b.age)a.age = 50print(b.age)

運行結果:

22066402853442206640285344Zhangsan 18Zhangsan 1850

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.