抽象工厂模式接口实现或类扩展 [英] Abstract factory pattern interface implementation or class extentsion

查看:252
本文介绍了抽象工厂模式接口实现或类扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前正在为数据库连接实现抽象工厂模式,我需要分离业务逻辑,并且需要为每个需要连接到我的应用程序的新数据库类型重写的代码
此时我有这些类

Im currently implementing an abstract factory pattern for database connectivity, I need to separate business logic, and have code that does not need to be rewritten for each new database-type that needs to connect to my application, So at this point I have these classes

Interface Connection{}
MySql implements Connection{}
PostgreSql implements Connection{}

所以这里的问题是每个实现接口Connection的类都必须重写方法在接口中,我需要一个类,其中有一些通用的方法,如setStatement,executeQuery等,但后来som方法需要重写像连接方法,这将根据数据库类型,

So the problem here is that each class that implements the interface Connection has to rewrite the methods in the interface, I would need a class where there are general methods like setStatement, executeQuery, etc, but then som methods would need to be overwritten like connect method which will differ depending on the databasetype,

我的第一个想法是在接口Connection和子类之间有一个额外的类
,其中的方法被保留和使用,如果没有重写,但这个解决方案不觉得正确的方式如果我错了)

My first thought is to have an extra class between the interface Connection and the subclasses, where the methods are kept and used if not overridden, but this solution does not feel like the right way (correct me if im wrong)

Interface ConnectionInterface{}
class Connection{}
MySql extends Connection{}
PostgreSql extends Connection{}

感谢

推荐答案

没有什么错。但我会这样做:

Nothing wrong with that. But I would do it like this:

interface Connection{}
abstract class AbstractConnection implements Connection {}
final class MySql extends AbstractConnection{}
final class PostgreSql extends AbstractConnection{}

一个完全替代的方法是一个类 DefaultConnectionOperations 提供的方法。然后你可以有一个这个类的对象,它被注入到每个Connection-Implementation中。但是有争议的是,如果在你的情况下依赖注入是必要的。

A completely alternative approach would be a class DefaultConnectionOperations that provides the methods. Then you could have an object of this class, which is injected into each Connection-Implementation. But it is arguable, if dependency injection is necessary in your case.

这篇关于抽象工厂模式接口实现或类扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆