Factory method template in java using generics, how?

I have a code that looks like this:

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 know that this code smells .. for many reasons. However, this code is also here: http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.html , see 9.8

I intend to do the following: 1) Switch my DAO implementations at runtime based on the environment (system properties). 2) Use java generics so that I can avoid type casting ... for example, does something like this:

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

Unlike:

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

Your thoughts and suggestions, please.

+5
source share
4 answers

factory :

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.

factory :

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

:

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

, , getInstance.

+10

, , :

, , DAOFactory (.. CustomerDAO getCustomerDAO()). , DAO , "", load()/get()/find() .

+6

BaseDAO, , DAOFactory.getCustomerDAO() CustomerDAO. , . :

interface DataAccess<T> {
  void store(T entity);
  T lookup(Serialiable identifier);
  void delete(Serializable identifier);
  Collection<? extends T> find(Criteria query);
}

abstract class DataAccessFactory {
  abstract DataAccess<T> getDataAccess(Class<T> clz);
  static DataAccessFactory getInstance() {
    ...
  }
}

- , DAO, . - . , JPA - API "", .

+5

, instanceof . :

CustomerDAO dao;
if (factory.getCustomerDAO() instanceof CustomerDAO) {
   dao = factory.getCustomerDAO();
}
dao.getCustomer();

, factory.getCustomerDAO() CustomerDAO (- ).

.

0

All Articles