我目前正在为应用程序创建数据访问层。该应用程序最初将连接到 Oracle 数据库,但稍后也会连接到 DB2 数据库。
为了连接到数据库,我将使用 JDBC。此时我正在考虑我的选择。在我看来,我有两个(主要)选择。
1) 创建一个支持多个 DAO 工厂的设计,每个工厂实例化特定于其数据库的 DAO。最初,该设计将只有一个工厂。稍后它将扩展第二个工厂和 DAO 类。
2) 创建一个 DAO 工厂,为不同模型实例化多个 DAO。该 DAO 工厂基于配置文件构建 DAO,其中包含 JDBC 驱动程序路径和连接 url。
我很想选择第二个选项,这似乎消除了 DAO 中的相当多的代码重复。谁能给出这两种方法的优缺点?
当您在使用 JDBC 时并不真正需要多个 DAO 工厂(抽象工厂模式)时,为什么要选择多个 DAO 工厂(抽象工厂模式)?
I'm currently in the process of creating a data access layer for an application. This application will initially connect to an Oracle database but will later also connect to a DB2 database.
For connecting to the database I will use JDBC. At this time I'm considering my options. As I see it I have two (primary) options.
1) Create a design with support for multiple DAO factories, each instantiating the DAO's specific to their database. Initially, this design will only have one factory. Later it will be extended with a second factory and DAO classes.
2) Create one DAO factory which instantiates multiple DAO's for the different models. This DAO factory builds the DAO's based on a configuration file, which contains the JDBC driver path and connection url.
I'm tempted to choose the second option, which seems to remove quite some code duplication in the DAO's. Could anyone give the pros and cons of both approaches?
Why would you choose for multiple DAO factories (abstract factory pattern) when you don't really need it when using JDBC?
发布评论
评论(2)
我相信 Spring 或 Guice 将是您最好、最干净的选择,您希望在其中选择适当的 DAO 实现并将其注入 DAO 消费者层。 Spring 还使您能够使用 Spring-JDBC,它负责处理大部分样板代码,使您的 DAO Impl 易于管理和编码。您还可以将 ORM 与 Spring 结合使用。
I believe Spring or Guice would be the best and cleanest option for you, where you'd want to pick the appropriate DAO implementation and inject it in the DAO consumer layer. Spring will also enable you to use Spring-JDBC which takes care of most of the boilerplate code making your DAO Impls easy to manage and code. You can also use ORMs with Spring.
考虑到你不能使用Spring(尽管它可以让你免于大量编码),我想说第二个变体更适合你,因为你将自己实现依赖管理和1个依赖(单个依赖) DAO 工厂)总是比 2 更容易。
不过,如果您预计两个数据库的 DAO 一起使用的位置并不大,那么将它们分成 2 个工厂将具有更好的结构意义并且更干净。但如果您期望,几乎每个使用 DAO 的类都需要两个世界(Oracle + DB2),那么再次坚持第二个变体。
无论如何,请尝试再次考虑依赖注入框架的使用,因为无论如何您都将在所有工厂中自行实现。
Taking into account that you can't use Spring (even though it would save you from a lot of coding), I would say that 2nd variant is more appropriate to you, because you are going to implement dependecy management yourself and 1 dependency (single DAO factory) is always easier than 2.
Though, if you expect that amount of places were DAOs for both databases are used together is not big, then separating them into 2 factories will have a better structural meaning and is more clean. But if you expect, that pretty much every class that uses DAOs will need both worlds (Oracle + DB2), then again stick to the 2nd variant.
In any case, try to consider again about dependecy injection framework usage, because that what you are going to implement yourself anyway with all your factories.