標籤:執行 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實現單例模式