最近我遇到了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方法的优缺点是什么?
答案 0 :(得分:4)
优点:
缺点: