问题描述
我的代码如下:
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..
}
}
现在,我知道这段代码闻起来有很多原因。但是,这段代码也是这样的:
,请参考9.8
Now, I do know that this code smells.. for many reasons. However, this code is here too:http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.html, refer 9.8
我打算做的是这样的:
1)开关我的DAO实现在运行时基于环境(系统属性)。
2)使用java泛型使我可以避免类型转换...
例如做这样的事情:
What I intend to do is this:1) Switch my DAOs implementations at runtime based on environment (system properties).2) Make use of java generics so that I can avoid type casting... for instance does something like this:
CustomerDAO dao = factory.getCustomerDAO();
dao.getCustomer();
相反:
CustomerDAO dao = (CustomerDAO) factory.getCustomerDAO();
dao.getCustomer();
请提供您的想法和建议。
Your thoughts and suggestions, please.
推荐答案
你应该定义这样的工厂:
You should define the factory like that:
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。
getInstance should return a proper typed DAOFactory.
工厂变量将具有以下类型:
The factory variable will have the type:
DAOFactory<CustomerDAO> factory = DAOFactory<CustomerDAO>.getInstance(CustomerDAO.class);
,使用情况将正确输入:
and the usage will be properly typed:
CustomerDAO dao = factory.getCustomerDAO();
dao.getCustomer();
唯一的问题可能是getInstance方法中需要的转换。
the only problem will probably be a cast required inside the getInstance methods.
这篇关于工厂方法模式在java中使用泛型,怎么办?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!