我有两个类extend
以非常类似的方式抽象类,我想抽象出常见的部分,因为我可能不得不再次使用它。它们每个都返回一个ThingLink
包含将它们链接到Parent
对象的数据。他们还返回Widget
,根据班级而有所不同,但仅限于他们的名字。这是模式:
public abstract class SomeClass extends TopClass {
protected abstract Widget createWidget();
public void someMethod() { // Does something }
}
public class ThingA extends SomeClass {
private static final String INFO_TYPE = "int";
public ThingLink newLink(Parent master, Int info) {
ThingLink link = new ThingLink(parent, ThingA.class);
link.addData(INFO_TYPE, info);
return link;
}
public Widget createWidget() {
// Stuff to get someData
return ThingAWidget.createMe(someData);
}
}
public class ThingB extends SomeClass {
private static final String INFO_TYPE = "String";
public ThingLink newLink(Parent master, String info) {
ThingLink link = new ThingLink(parent, ThingB.class);
link.addData(INFO_TYPE, info);
return link;
}
public Widget createWidget() {
// Stuff to get someData
return ThingBWidget.createMe(someData);
}
}
我无法访问TopClass
,ThingLink
类或Widget
类。我试图使用泛型来抽象出常见的部分,但我似乎无法弄清楚这是否会提供完整的解决方案。我最大的问题是弄清楚如何获得自我指涉的碎片。我想上课一样:
public abstract class Thing<T> extends SomeClass {
private String infoType;
public void setInfoType(String type) { infoType = type; }
public ThingLink newLink(Parent master, T info {
ThingLink link = new ThingLink(parent, ???????????);
link.addData(infoType, info);
return link;
}
public Widget createWidget() {
// Stuff to get someData
return ??????????????.createMe(someData);
}
}
请记住,我对Java很新,并且自学成才,但我正在努力做出更大的飞跃,并且真正理解如何编写好的代码。感谢您的帮助。