设计模式——工厂模式使用

以操作数据库为例,有两个类:一个操作MySQL,另一个类操作Oracle,这两个类都有相同的方法,另外还有一个数据库工厂,用于制造某一数据库的对象。
上代码:

# database包中有一个dao模块,用于实现操作数据库,里面会有query、execute等方法:
# dao.py

class MySQLConnection:
	"""实例化时,只有一个单例,并且是使用数据库连接池"""
	def __init__(self):
		""""""

	def query(self, *args, **kwargs):
		""""""
		

class OracleConnection:
	def __init__(self):
		""""""

	def query(self, *args, **kwargs):
		""""""
# databases.py

# 从database包dao模块中引入 python操作MySQL的类
from database.dao import MySQLConnection
# 从database包dao模块中引入 python操作Oracle的类
from database.dao import OracleConnection


class DataBaseFactory(object):

	def __init__(self, type='mysql'):
		"""

		:param type: 数据库的类型,取值:mysql oracle 等
		"""
		self.type = type

	def produce_dao(self):

		type = self.type.strip().lower()

		if type == 'mysql':
			dao = MySQLConnection()
		elif type == 'oracle':
			dao = OracleConnection()
		elif type == 'sqlite':
			pass
		else:
			raise Exception("type参数是不支持的数据库类型")
		return dao


if __name__ == '__main__':
        # 测试
	dao = DataBaseFactory(type='mysql'). produce_dao()
	print(dao)

	ret = dao.query(sql)
	print(ret)

在代码中使用时,在入口文件引入DataBaseFactory类,实例化一对象dao(dao = DataBaseFactory(type='mysql'). produce_dao()),即可在代码中使用dao去操作数据库了,这个dao在代码各处只有这一个对象。

以上。

原文地址:https://www.cnblogs.com/lovebkj/p/14582311.html