Python 抽象工厂模式连接数据库示例
好的,下面是一个示例的抽象工厂模式连数据库的代码:
# 抽象产品接口
class Database:
def connect(self):
pass
def disconnect(self):
pass
def execute_query(self, query):
pass
# 具体产品类 - MySQL数据库
class MySQLDatabase(Database):
def connect(self):
print('连接到MySQL数据库')
def disconnect(self):
print('从MySQL数据库断开连接')
def execute_query(self, query):
print('在MySQL数据库中执行查询:%s' % query)
# 具体产品类 - PostgreSQL数据库
class PostgreSQLDatabase(Database):
def connect(self):
print('连接到PostgreSQL数据库')
def disconnect(self):
print('从PostgreSQL数据库断开连接')
def execute_query(self, query):
print('在PostgreSQL数据库中执行查询:%s' % query)
# 抽象工厂接口
class DatabaseFactory:
def create_database(self):
pass
# 具体工厂类 - MySQL数据库工厂
class MySQLDatabaseFactory(DatabaseFactory):
def create_database(self):
return MySQLDatabase()
# 具体工厂类 - PostgreSQL数据库工厂
class PostgreSQLDatabaseFactory(DatabaseFactory):
def create_database(self):
return PostgreSQLDatabase()
# 客户端代码
def client_code(database_factory):
database = database_factory.create_database()
database.connect()
database.execute_query('SELECT * FROM table')
database.disconnect()
# 使用MySQL数据库
mysql_factory = MySQLDatabaseFactory()
client_code(mysql_factory)
# 使用PostgreSQL数据库
postgresql_factory = PostgreSQLDatabaseFactory()
client_code(postgresql_factory)
上述代码是一个简单的示例,演示了如何使用抽象工厂模式创建不同类型的数据库连接,并执行查询操作。在代码中,我们定义了抽象产品接口Database,具体产品类MySQLDatabase和PostgreSQLDatabase实现了该接口。抽象工厂接口DatabaseFactory定义了创建数据库产品的方法,具体工厂类MySQLDatabaseFactory和PostgreSQLDatabaseFactory实现了该接口。
在客户端代码中,我们可以根据需要选择不同的数据库工厂,并通过工厂创建数据库对象。然后我们可以使用数据库对象的方法连接到数据库、执行查询以及断开连接。
请注意,以上示例只是一个简单的示例,实际中可以根据需要进行扩展和优化。
原文地址: https://www.cveoy.top/t/topic/bEam 著作权归作者所有。请勿转载和采集!