public interface MyMapperInterface<Y, Z> {
Y map(Z zObject);
}
public class One{
}
public class Two{
}
public MapperOneTwo implements MyMapperInterface<One, Two> {
public One map(Two twoObject){
//Based on properties of Two, a new One Object is created and returned.
}
}
public MapperThreeFour implements MyMapperInterface<Three, Four> {
public One map(Two twoObject){
//Now for two other class, Three and Four, there is a new
mapper.
Based on properties of Two, a new One Object is created and
returned.
}
}
FactoryClass
public class Factory {
public <T> T getClassInstance(String params){
if (params.equals("a")) {
return (T) new MapperOneTwo();
} else if (params.equals("b")){
return (T) new MapperThreeFour();
}
}
}
用法我有一个处理程序类,它需要映射并传递其他类型。所以我希望将类型传递给工厂,然后工厂提供相应的映射器,然后该映射器完成其工作并返回相应类型的对象。但问题是现在返回的对象是 Object 类型,并且这个处理程序类必须在进一步传递它之前对其进行类型转换。
有没有办法避免类型转换并且仍然能够创建这样的工厂?
谢谢
以下工厂将解决上述问题,而无需进行类型转换:
public class Factory {
public <Y, Z> Mapper<Y, Z> create(Class<Y> yClassType) {
Mapper mapper;
if (yClassType.equals(One.class)) {
mapper = new MapperOneTwo();
} else {
//Handle default behaviour
}
return mapper;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句