我有以下对象
interface Adapter<T> {
T fromXml(XML xml);
XML toXml(T obj); //ignoring this in implementations
}
abstract class AbstractAdapter<T> implements Adapter<T>{
T fromXml(XML xml) { //template method
validate(xml);
return parse(xml);
}
abstract void validate(Xml xml);
abstract T parse(Xml xml);
}
class MyObjectAdapter extends AbstractAdapter<MyObject> {
MyObject parse(XMl xml) {return null;}
void validate(Xml xml) {}
}
class AnotherObjectAdapter extends AbstractAdapter<AnotherObject> {
AnotherObject parse(XMl xml) {return null;}
void validate(Xml xml) {}
}
class AdapterFactory {
Adapter<?> createAdapter(String objectType) {
if (objectType == "MyObject") return new MyObjectAdapter();
if (objectType == "AnotherObject") return new AnotherObjectAdapter();
}
public static void main(String args[]) {
AdapterFactory factory = new AdapterFactory();
//********
Adapter<MyObject> myobjectAdapter = (Adapater<MyObject>) factory.createAdapter("MyObject");
MyObject obj = myobjectAdapter.fromXml(getXml(args));
}
如何避免在上面标有* *的行中进行向下转换?需要适配器的对象之间没有任何关系,它们是通用数据对象。