我的代码如下所示:
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 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();
请提出您的想法和建议。
你应该这样定义工厂:
public abstract class DAOFactory<DAO extends BaseDAO> {
public DAO getCustomerDAO();
public static <DAO extends BaseDAO> DAOFactory<DAO> getInstance(Class<DAO> typeToken){
// instantiate the the proper factory by using the typeToken.
if(system.getProperty("allowtest").equals("yes")) {
return new TestDAOFactory();
}
else return new ProdDAOFactory();
}
getInstance 应该返回一个正确类型的 DAOFactory。
工厂变量的类型为:
DAOFactory<CustomerDAO> factory = DAOFactory<CustomerDAO>.getInstance(CustomerDAO.class);
并且用法将被正确键入:
CustomerDAO dao = factory.getCustomerDAO();
dao.getCustomer();
唯一的问题可能是 getInstance 方法内部需要进行强制转换。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)