單例模式
1. 單例是什么
舉個常見的單例模式例子,我們日常使用的電腦上都有一個回收站,在整個作業系統中,回收站只能有一個實體,整個系統都使用這個唯一的實體,而且回收站自行提供自己的實體,因此回收站是單例模式的應用,
確保某一個類只有一個實體,而且自行實體化并向整個系統提供這個實體,這個類稱為單例類,單例模式是一種物件創建型模式,
2. 創建單例-保證只有1個物件
# 實體化一個單例
class Singleton(object):
__instance = None
def __new__(cls, age, name):
#如果類屬性__instance的值為None,
#那么就創建一個物件,并且賦值為這個物件的參考,保證下次呼叫這個方法時
#能夠知道之前已經創建過物件了,這樣就保證了只有1個物件
if not cls.__instance:
cls.__instance = object.__new__(cls)
return cls.__instance
a = Singleton(18, "dongGe")
b = Singleton(8, "dongGe")
print(id(a))
print(id(b))
a.age = 19 #給a指向的物件添加一個屬性
print(b.age)#獲取b指向的物件的age屬性
運行結果:
In [12]: class Singleton(object):
...: __instance = None
...:
...: def __new__(cls, age, name):
...: if not cls.__instance:
...: cls.__instance = object.__new__(cls)
...: return cls.__instance
...:
...: a = Singleton(18, "dongGe")
...: b = Singleton(8, "dongGe")
...:
...: print(id(a))
...: print(id(b))
...:
...: a.age = 19
...: print(b.age)
...:
4391023224
4391023224
19
3. 創建單例時,只執行1次__init__方法
# 實體化一個單例
class Singleton(object):
__instance = None
__is_first = True
def __new__(cls, age, name):
if not cls.__instance:
cls.__instance = object.__new__(cls)
return cls.__instance
def __init__(self, age, name):
if self. __is_first:
self.age = age
self.name = name
Singleton. __is_first = False
a = Singleton(18, "習大大")
b = Singleton(28, "習大大")
print(id(a))
print(id(b))
print(a.age)
print(b.age)
a.age = 19
print(b.age)
運行結果:

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/39731.html
標籤:Python
