2

Recently I came across code where DAO has an instance of DAOFactory. And DAOFactory has Connection. DAO uses Connection of DAOFactory for its operations. Basically DAO was dependent on DAOFactory. This is the code:

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;
   }
}

I usually see DAO have Connection but this one have DAOFactory instead.

What are the pros and cons of using this approach of DAO having DAOFactory compared to DAO having Connection?

srh
  • 1,427
  • 3
  • 22
  • 45

2 Answers2

4

Pros :

  1. Creates objects according to the required database connection.
  2. Then according to the created database creates the User.
  3. Follows standard Abstract Factory Design Pattern.

Cons:

  1. There is no need to have seperate UserDAOs for separate connections. Could have been done with one class.
Pritam Banerjee
  • 15,297
  • 10
  • 71
  • 92
2

The DAO having a DAOFactory means that changing the connection in the factory will change the connection in every dao created from it. This allows the DAOs to be created before the connection instance is known.

It has the disadvantages of creating circular dependencies between DAOFactory and the DAOs, and causing the DAOs to have more dependencies than they need, which can increase the complexity of the code.

fgb
  • 17,739
  • 2
  • 33
  • 50