【发布时间】:2014-04-14 17:31:11
【问题描述】:
目前我的班级看起来像这样(非常简化):
我有三个类来描述节点或方式(来自 OpenStreetMap):
public abstract class Geometry {
private String id;
public Geometry(String id) {
this.id = id;
}
}
public class Node extends Geometry {
private GeoPoint location;
public Point(String id, GeoPoint location) {
super(id);
this.location = location;
}
public GeoPoint getLocation() {
return location;
}
}
public class Ways extends Geometry {
private ArrayList <GeoPoint> shape;
public Point(String id, ArrayList <GeoPoint> shape) {
super(id);
this.shape = shape;
}
public GeoPoint getShape() {
return shape;
}
}
现在我想用类 Geometry 遍历一个 ArrayList 并使用两个子类中的方法:
private void prepareList(ArrayList<Geometry> geometries) {
for (Geometry m : geometries) {
if (m.getClass().equals(Node.class)) {
location = m.getLocation();
}
else if (m.getClass().equals(Way.class)) {
shape = m.getShape();
}
}
}
在我的解决方案中,我需要在 Geometry 类中创建一些虚拟方法来访问这些方法,例如 公共地理点getLocation(){ 返回空值; }
我现在的问题是,在 Java 中实现这一点的最佳方法是什么,而不需要创建单独的类(这会导致代码重复)或编写这个“虚拟”方法。有没有更好的办法?
【问题讨论】:
-
instanceof是你的朋友。我确实阅读了您的问题 3 次,很抱歉,但我不明白。您能否详细说明(您在说什么虚拟方法)?也许您应该发布您拥有的代码(使用虚拟方法) -
如果您要对几何进行类型检查,您可以对其进行类型转换并调用适当的方法。即:
if (m instanceof Node) { location = ((Node)m).getLocation() }虽然我不确定这是否是最好的设计。最好看看能不能做一个两个类都实现的抽象方法。 -
如果可能的话,我会避免使用 instanceof。这是一个很好的迹象,表明您不是在编写 OO
-
您可以考虑使用此帖子link 的答案中描述的访问者模式。我认为这可能是最好的选择。
-
@Amir 我完全同意,这基本上就是他最初所做的。这就是我链接访客模式的原因。
标签: java inheritance