最近,我遇到了DAO具有DAOFactory实例的代码。和DAOFactory具有连接。 DAO使用DAOFactory的Connection进行操作。基本上,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。
与具有Connection的DAO相比,使用具有DAOFactory的DAO的这种方法的优缺点是什么?
最佳答案
具有DAOFactory的DAO意味着更改工厂中的连接将更改由此创建的每个dao中的连接。这允许在知道连接实例之前创建DAO。
它的缺点是在DAOFactory和DAO之间创建循环依赖关系,并导致DAO具有比其所需更多的依赖关系,这会增加代码的复杂性。