DAO的优缺点依赖于DAOFactory

时间:2015-12-20 01:58:33

标签: java dao genericdao

最近我遇到了DAO有DAOFactory实例的代码。 DAOFactory有Connection。 DAO使用DAOFactory连接进行操作。基本上DAO依赖于DAOFactory。这是代码:

DAOFactory.java:

public abstract class DAOFactory {
   public static final int SQL_SERVER = 1;
   public static final int MY_SQL = 2;
   private Connection connection = null;

   public static DAOFactory getDAOFactory(int daoFactoryType) {
      DAOFactory daoFactory = null;

      switch (daoFactoryType) {
         case SQL_SERVER:
            daoFactory = new SQLServerDAOFactory();            
            break; 
         case MY_SQL:
            daoFactory = new MySQLDAOFactory(); 
            break; 
      }

      return daoFactory;
   }

   public Connection getConnection() {
      return connection;
   }
   public void setConnection(Connection connection) {
      this.connection = connection;
   }

   public abstract UserDAO getUserDAO();
   ...  
}

BaseDAO.java:

public abstract class BaseDAO {
   protected DAOFactory daoFactory;

   public BaseDAO(DAOFactory daoFactory) {
      this.daoFactory = daoFactory;
   }
}

UserDAO.java:

public interface UserDAO {
   public User getUserById(int userId) throws DAOException;
   ...
}

SQLServerUserDAO.java:

public class SQLServerUserDAO extends BaseDAO implements UserDAO {
   public SQLServerUserDAO (DAOFactory daoFactory) {
      super(daoFactory);
   }

   @Override
   public User getUserById(int userId) throws DAOException {
      // it uses the connection this way: this.daoFactory.getConnection();
      // implementation 
   }
}

SQLServerDAOFactory.java:

public final class SQLServerDAOFactory extends DAOFactory {
   @Override
   public UserDAO getUserDAO() {
      UserDAO userDAO = null;

      userDAO = new SQLServerUserDAO(this);
      return userDAO;
   }
}

我经常看到DAO有Connection,但是这个有DAOFactory。

与具有连接的DAO相比,使用这种具有DAOFactory的DAO方法的优缺点是什么?

1 个答案:

答案 0 :(得分:4)

优点:

  1. 根据所需的数据库连接创建对象。
  2. 然后根据创建的数据库创建User。
  3. 遵循标准的抽象工厂设计模式。
  4. 缺点:

    1. 不需要为单独的连接分别使用UserDAO。可以用一个班级来完成。