正如Florian所說,您希望創建一個接口Graphable
並使J48Tree
和RandomTree
都能實現它。
public interface Graphable {
void graph();
}
public class J48Tree extends AbstractTree implements Graphable {
@Override
public void graph() {
// implementation
}
}
public class RandomTree extends AbstractTree implements Graphable {
@Override
public void graph() {
// implementation
}
}
public class Visualization {
private Graphable graphable;
public void setGraphable(Graphable graphable) {
this.graphable = graphable;
}
public void graph() {
this.graphable.graph();
}
}
然後,您可以通過調用setGraphable
設置Visualization
類Graphable
實現。
編輯
從您的評論我知道你是不是能夠做出既不J48Tree
也不RandomTree
實現Graphable
接口(這是你必須做的類唯一的變化)。在這種情況下,您應該將每個類的實例'包裝'到另一個類中,該類實現了Graphable
。現在
public interface Graphable {
void graph();
}
public class J48TreeWrapper implements Graphable {
private final J48Tree j48Tree;
public J48TreeWrapper(J48Tree j48Tree) {
this.j48Tree = j48Tree;
}
@Override
public void graph() {
this.j48Tree.graph();
}
}
public class RandomTreeWrapper implements Graphable {
private final RandomTree randomTree;
public RandomTreeWrapper(RandomTree andomTree) {
this.randomTree = randomTree;
}
@Override
public void graph() {
this.randomTree.graph();
}
}
public class Visualization {
private Graphable graphable;
public void setGraphable(Graphable graphable) {
this.graphable = graphable;
}
public void graph() {
this.graphable.graph();
}
}
,你會先有「包」一個J48Tree
創造J48TreeWrapper
一個實例,然後你使用它(與相同RandomTreeWrapper
)調用setGraphable
。
public static void main(String[] args) {
J48TreeWrapper wrapper = new J48TreeWrapper(new J48Tree());
Visualization visualization = new Visualization();
visualization.setGraphable(wrapper);
visualization.graph();
}
爲您的兩個類添加'Graphable'接口,並在'Visualization'類中使用''graph()'方法。 –