最近我遇到了 DAO 有一个 DAOFactory 实例的代码。并且 DAOFactory 有 Connection。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;
}
}
用户DAO.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 方法的优缺点是什么?