编程中,有许多设计模式,在学习python中,第一次接触到了单例模式.
单例模式应用场景:
同一个类中相同的方法和变量,因为需求,需要多次创建.
多次创建同一个实例,极大的浪费内存.
静态方法,静态变量.
注意:下面的代码运行在py27版本中
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 = 330610 self.pwd = "123456"11 self.username="root"12 self.conList = [1,2,3,4,5,6,7,8,9]13 @staticmethod14 def getInstance():15 if connPool.__instance:16 return connPool.__instance17 else:18 connPool.__instance=connPool()19 return connPool.__instance20 def getConn(self):21 #获取连接22 # print(self.conList)23 res = random.randrange(1,11)24 return res25 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 ret40 elif url.endswith("news"):41 ret = news()42 return ret43 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() ##