简体   繁体   中英

DAOFactory automatic type casting. java

I have a DAOFactory which returning me a specific dao

public class DAOFactory {

public static final int DAO1 = 1;
public static final int DAO2 = 2;

public static Object getDao(int dao) {
        switch (dao) {
            case DAO1:
                return new Dao1();
            case DAO2:
                return new Dao2();
        }
        return null;
    }
}

Dao is child of

abstract class GenericDao<E, ID extends Serializable> implements
        GenericDaoInterface<E, ID>

So it looks like:

public class Dao1 extends GenericDao<Dao1, Integer>{
....
}

And If I create new dao. I must do type casting.

Dao1 dao = (Dao1) DAOFactory.getDao(DAOFactory.DAO1);

Is it possible to make automatic type casting or it is better to make methods in DAOFactory to call specific dao ? eg. public static Dao1 getDao1()

Make an interface IGenericDao and implements it on GenericDao, the factory must return IGenericDao interface, by this way you could use generic behaviour of all Dao or cast to a specific type when need it, use the Class instead an int to the parameter to the factory method.

public static IGenericDao getDao(Class)

Another reason to use only one method is that in a future implementation you could implement the factory using reflection and return dinamicaly the correct type and you don't need to change all the clients of the factory.

You could change the "int" argument to a "Class" one, then use generics to return something of that class.
But this would only be useful if sometimes your code doesn't know what DAO class it was going to use, eg some generic code which needs to grab an arbitrary DAO subtype from the factory.

If you code is quite specific then you could just create those specific methods that you mention.

IMHO people get hung up on generics.
Sometimes generics code looks horrible and a type cast or two is fine and often preferable. Just IMHO as I say.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM