最近做了项目中的数据库连接的优化工作,用到了数据库连接池,便想起了用单例模式来实现。下面给出单例模式的简单介绍和源码。
一、单例模式
单例模式的作用在于保证整个程序在一次运行的过程中,被单例模式声明的类的对象要有且只有一个。
单例模式应用的关键有两点:
1、构造方法私有化。这样就可以隐藏构造方法,别人就无法通过构造方法获取实例对象。
2、一个获取实例对象的静态方法。想要获取实例对象,只能通过这个方法来获取。
二、实现代码
#!/usr/bin/python
#encoding=utf-8
import MySQLdb
from DBUtils.PooledDB import PooledDB
class dbPool():
__instance=None
def __init__(self):
self.__instance=PooledDB(MySQLdb, 5, host='localhost', user='root',
passwd='123456', db='test',
port=3306 ,maxconnections=5,charset='utf8')
@staticmethod
def get_instance():
if None==dbPool.__instance:
dbPool.__instance = dbPool()
return dbPool.__instance
def get_connection(self):
return self.__instance.connection()