正如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()'方法。 –