歡迎關注【無量測試之道】公衆號,回覆【領取資源】,
Python編程學習資源乾貨、
Python+Appium框架APP的UI自動化、
Python+Selenium框架Web的UI自動化、
Python+Unittest框架API自動化、
資源和代碼 免費送啦~
文章下方有公衆號二維碼,可直接微信掃一掃關注即可。
Step1: 什麼是設計模式?
設計模式(Design pattern)是一套被反覆使用、多數人知曉的、經過分類編目的、代碼設計經驗的總結。使用設計模式是爲了可重用代碼、讓代碼更容易被他人理解、保證代碼可靠性。
Step2: 單例模式的代碼實現如下
class singleton(object): # 創建一個類
mysingleton = None
def __new__(self, *args, **kwargs): #重寫__new__方法
if self.mysingleton is None:
self.mysingleton = object.__new__(self) #調用用object類的__new__方法創建實例
return self.mysingleton #返回實例
else:
return self.mysingleton#返回實例,與上面的返回相同
if __name__ == "__main__":
a = singleton() #實例化一個a對象
b = singleton() #實例化一個b對象
print(id(a)) #id() 函數返回對象的唯一標識符,標識符是一個整數。
print(id(b)) #如果兩個一樣就說明是同一個實例化對象
Step3: 單例模式的的應用場景有哪些?
數據庫連接池,日誌logger插入,計時器、權限校驗、網站計數器,windows資源管理器,回收站,線程池等資源池。
Step4: 以數據庫連接池爲示例進行代碼演示如下
import dbconfig
import pymysql
class singleton(object):
dbconn = None
def __new__(self, *args, **kwargs):
dbname=args
if self.dbconn is None:
self.dbconn = pymysql.connect(dbconfig.dbDict.get(dbname[0]), dbconfig.dbUser, dbconfig.dbPassword).cursor()
print("aaa")
return self.dbconn
else:
print("bbb")
return self.dbconn
if __name__ == "__main__":
test = singleton("ars1")
result =test.execute("select id,code from info.property where status=1")
print(test.fetchall())
print(id(test))
test1 = singleton("ars1")
result1 = test1.execute("select id,code from info.property where status=1")
print(test1.fetchall())
print(id(test1))
備註:我的個人公衆號已正式開通,致力於測試技術的分享,包含:大數據測試、功能測試,測試開發,API接口自動化、測試運維、UI自動化測試等,微信搜索公衆號:“無量測試之道”,或掃描下方二維碼:
添加關注,一起共同成長吧。