简体   繁体   English

DAOFactory自动类型铸造。 java的

[英]DAOFactory automatic type casting. java

I have a DAOFactory which returning me a specific dao 我有一个DAOFactory可以返回一个特定的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. 如果我创建新的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 ? 是否可以进行自动类型转换,还是最好在DAOFactory中使方法调用特定的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. 创建一个接口IGenericDao并在GenericDao上实现,工厂必须返回IGenericDao接口,这样您可以使用所有Dao的泛型行为,或在需要时将其强制转换为特定类型,使用Class代替工厂参数的int方法。

public static IGenericDao getDao(Class) 公共静态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. 您可以将“ int”参数更改为“ 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. 但这仅在有时您的代码不知道它将使用什么DAO类时才有用,例如某些通用代码需要从工厂获取任意DAO子类型。

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. 正如我所说的,恕我直言。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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