1

我有以下对象

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)); 
}

如何避免在上面标有* *的行中进行向下转换?需要适配器的对象之间没有任何关系,它们是通用数据对象。

4

1 回答 1

1

您在 a 中有一个类名,String并且您正试图从该类名转到实际类型。那总是会涉及演员表。如果您删除AdapterFactory,因此删除String,则没有问题。

(通常注意==on Strings 通常不是您想要的。)

于 2012-08-02T19:41:52.103 回答