一、單例模式要點
一 是某個類只能有一個實例
二 是它必須自行創(chuàng)建這個實例
三 是它必須自行向整個系統(tǒng)提供這個實例‘
四 單例中無論創(chuàng)建幾個對象,都是對同一個內(nèi)存對象進行操作的
單例模式 :確保某一個類只有一個實例,而且自行實例化并向整個系統(tǒng)提供這個實例,這個類稱為單例類,單例模式是一種對象創(chuàng)建型模式。
單例模式 簡單代碼及魔法方法
class Test(object):
__instance = None
def __init__(self): #初始化屬性
print("----init方法----")
def __del__(self): #刪除對象調(diào)用
print("----del方法----")
def __str__(self): #打印對象調(diào)用,要有返回值
print("----str方法----")
def __new__(cls): #創(chuàng)建對象,并返回對象引用
print("----new方法----")
if cls.__instance == None:
cls.__instance = object.__new__(cls)
return cls.__instance
test1 = Test()
print(id(test1))
test2 = Test()
print(id(test2))
# 實例化一個單例
class Singleton(object):
__instance = None
__first_init = False
def __new__(cls, age, name):
if not cls.__instance:
cls.__instance = object.__new__(cls)
return cls.__instance
def __init__(self, age, name):
if not self.__first_init:
self.age = age
self.name = name
Singleton.__first_init = True
a = Singleton(18, "dongGe")
b = Singleton(8, "dongGe")
print(id(a))
print(id(b))
print(a.age)
print(b.age)
a.age = 19
print(b.age)
運行結(jié)果:
ubuntu@ubuntu-VirtualBox:~/桌面/2_1805/13day$ python3 01-簡書單例模式.py 140168837839672
140168837839672
18
18
19
單例模式優(yōu)點
使用 設計模式 是為了可重用代碼、讓代碼更容易被他人理解、保證代碼可靠性