java 泛型 工厂,工厂方法模式在java中使用泛型,怎么办?

代码示例展示了一个基于环境属性动态选择DAO实现的工厂模式,同时提出了利用Java泛型避免类型转换的需求。作者意识到代码存在一些问题,并引用了Java官方蓝prints中的DAO模式作为参考。目标是在运行时根据环境切换DAO实现,并利用泛型提高代码类型安全性。
摘要由CSDN通过智能技术生成

I have code that looks like follows:

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..

}

}

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

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();

As opposed to:

CustomerDAO dao = (CustomerDAO) factory.getCustomerDAO();

dao.getCustomer();

Your thoughts and suggestions, please.

解决方案

You should define the factory like that:

public abstract class DAOFactory {

public DAO getCustomerDAO();

public static DAOFactory getInstance(Class typeToken){

// instantiate the the proper factory by using the typeToken.

if(system.getProperty("allowtest").equals("yes")) {

return new TestDAOFactory();

}

else return new ProdDAOFactory();

}

getInstance should return a proper typed DAOFactory.

The factory variable will have the type:

DAOFactory factory = DAOFactory.getInstance(CustomerDAO.class);

and the usage will be properly typed:

CustomerDAO dao = factory.getCustomerDAO();

dao.getCustomer();

the only problem will probably be a cast required inside the getInstance methods.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值