我的代码如下所示:
public interface BaseDAO{
// marker interface
}
public interface CustomerDAO extends BaseDAO{
public void createCustomer();
public void deleteCustomer();
public Customer getCustomer(int id);
// etc
}
public abstract class DAOFactory {
public BaseDAO getCustomerDAO();
public static DAOFactory getInstance(){
if(system.getProperty("allowtest").equals("yes")) {
return new TestDAOFactory();
}
else return new ProdDAOFactory();
}
public class TestDAOFactory extends DAOFactory{
public BaseDAO getCustomerDAO() {
return new TestCustomerDAO(); // this is a concrete implementation
//that extends CustomerDAO
//and this implementation has dummy code on methods
}
public class ProdDAOFactory extends DAOFactory {
public BaseDAO getCustomerDAO() {
return new ProdCustomerDAO(); // this implementation would have
// code that would connect to the database and do some stuff..
}
}
现在,我知道这段代码有异味……有很多原因。但是,此代码也在这里: http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.html,请参阅 9.8
我打算做的是:1)根据环境(系统属性)在运行时切换我的 DAO 实现。2)利用java泛型,这样我就可以避免类型转换......例如做这样的事情:
CustomerDAO dao = factory.getCustomerDAO();
dao.getCustomer();
相对于:
CustomerDAO dao = (CustomerDAO) factory.getCustomerDAO();
dao.getCustomer();
请提出您的想法和建议。