DAO/抽象工厂模式 - 多个数据源

3

我目前使用抽象工厂模式设置了一些DAO。代码如下:

public abstract class DaoFactory
    public static GetDaoFactory()
    public abstract IPersonDao GetPersonDao()
    // etc.

静态方法GetDaoFactory()返回底层的SqlDaoFactory。直到今天,所有的DAO都使用同一个SQL数据库。现在,我想向该工厂添加另一个DAO,但是该DAO将与外部服务交互而不是SQL数据库(假设这是GetCompanyDao())。我基本上只想将此GetCompanyDao()方法添加到抽象DaoFactory类中,以便公共接口完全解耦从底层实现(无需/无法告知特定dao是使用SQL还是外部服务)。
我应该简单地将SqlDaoFactory重命名为更合适的名称,并在其中包含GetCompanyDao()方法,以便该DAO工厂现在对某些DAO使用SQL,对其他DAO使用外部服务?还是有其他方法可以实现这一点?
4个回答

3

你可以将其重命名,这完全取决于你。DAO模式抽象了任何类型的数据访问,不一定是数据库访问。因此,你可以继续执行你的计划。

你可以使用像Spring这样的框架来代替手动创建模式。

我曾经试过硬编码这些模式,但只有一次。

public abstract class DAOFactory {

  // List of DAO types supported by the factory
  public static final int MYSQL = 1;
  public static final int ORACLE = 2;
  public abstract UserDAO getUserDAO() throws SQLException;
  public static DAOFactory getDAOFactory(int whichFactory) {

    switch (whichFactory) {
      case MYSQL: 
          return new MySQLDAOFactory();
      case ORACLE    :
          ......


public class MySQLDAOFactory extends DAOFactory {

    public MySQLDAOFactory() {
    }
    public static final String DRIVER= "/*driver here*/";
    public static final String DBURL="/*conn string here*/";
    /* instead of using constants you could read them from an external xml file*/

    public static Connection createConnection() {
        /*create connection object here*/
        return conn;
    }
    public UserDAO getUserDAO() throws SQLException{
        return new MySQLUserDAO();
    }

public interface UserDAO {
    public int insertUser(String fname, String lname);
    public ArrayList<User> selectUsers();
}

public class MySQLUserDAO implements UserDAO {

    Connection conn=null;
    Statement s=null;
    public MySQLUserDAO() throws SQLException{
        conn = MySQLDAOFactory.createConnection();
        s = conn.createStatement();
    }

    public int insertUser(String fname, String lname) 
    {
        //implementation
    }


    public ArrayList<User> selectUsers() 
    {
        //implementation
    }

3

你是否考虑过 策略模式。SQL或外部服务访问逻辑可以实现为具体策略,而用户只需看到策略接口。


1
考虑使用依赖注入容器(如Spring框架)来获取预配置的DAO或其他类型服务的引用。例如,在Spring中,您可以编写一个XML文件来定义访问Oracle数据库的DAO,另一个文件定义访问另一个数据库供应商的DAO:只需使用适当的版本部署即可使应用程序正常工作。
此外,有两点需要注意:
1)虽然DAO模式的意图是抽象出任何类型的数据源(数据库、Web服务、属性文件等),但它通常仅与数据库访问相关联。您可以将任何其他数据源访问层定义为“服务”对象。
2)顺带一提,除非您实际上计划部署应用程序以使用不同的数据源(现在或将来),否则引入工厂对象以及每个DAO的通用DAO接口是没有意义的。

0
你可以像这样做 this。看看图9.8。 所以你实际上要做的是更改抽象类中的GetDaoFactory方法,以接受表示你想要哪个工厂的参数,SqlDaoFactory或ExternalServiceDaoFactory。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接