編程中,有許多設計模式,在學習python中,第一次接觸到了單例模式.html
單例模式應用場景:python
同一個類中相同的方法和變量,由於需求,須要屢次建立.web
屢次建立同一個實例,極大的浪費內存.編程
靜態方法,靜態變量.設計模式
注意:下面的代碼運行在py27版本中dom
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 from wsgiref.simple_server import make_server 4 def RunServer(environ,start_response): 5 start_response(status="200 ok",headers=[('Content-Type','text/html')]) 6 url=environ['PATH_INFO'] 7 return "OldBoy xurui" 8 if __name__ == '__main__': 9 httpd = make_server('',8000,RunServer) 10 print("Serving HTTP on port 8000....") 11 httpd.serve_forever()
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 from wsgiref.simple_server import make_server 4 import random 5 class connPool: 6 __instance =None 7 def __init__(self): 8 self.ip = '1.1.1.1' 9 self.port = 3306 10 self.pwd = "123456" 11 self.username="root" 12 self.conList = [1,2,3,4,5,6,7,8,9] 13 @staticmethod 14 def getInstance(): 15 if connPool.__instance: 16 return connPool.__instance 17 else: 18 connPool.__instance=connPool() 19 return connPool.__instance 20 def getConn(self): 21 #獲取鏈接 22 # print(self.conList) 23 res = random.randrange(1,11) 24 return res 25 def index(): 26 # obj = connPool() ##建立了多個實例 27 # print(obj) 28 p = connPool.getInstance() ##建立一個同一個實例/對象 29 print(p) 30 return "index11111" 31 def news(): 32 return "news22222" 33 def RunServer(environ,start_response): 34 start_response(status="200 ok",headers=[('Content-Type','text/html')]) 35 url=environ['PATH_INFO'] 36 print(url) 37 if url.endswith("index"): 38 ret = index() 39 return ret 40 elif url.endswith("news"): 41 ret = news() 42 return ret 43 else: 44 return "404" 45 return "OldBoy xurui1" 46 if __name__ == '__main__': 47 httpd = make_server('',8000,RunServer) 48 print("Serving HTTP on port 8000....") 49 httpd.serve_forever() ##