我正在为学校做一个项目,挑战我对OOP的理解。我有同一个类的多个对象,城市。每个城市都有自己的位置。如果我的理解是正确的,因为每个城市之间的距离依赖于另一个城市,"int距离“不能是类城市中的一个字段。我可以编写一个方法来计算每个城市之间的距离,但是我不知道如何/在哪里保存这些数据。我希望最终对这些数据进行排序,以找出哪些City对象最接近。
发布于 2015-11-27 01:48:57
在我看来,距离的计算应该是Location的方法,而不是City的方法。你以后可以决定你的地图有其他感兴趣的地方,除了城市,也有一个位置。
因此,我对结构的建议是:
interface PointOfInterest {
Location getLocation();
default int distanceTo(PointOfInterest other) {
return getLocation().distanceTo(other.getLocation());
}
}
class City implements PointOfInterest {
private final Location location;
@Override public Location getLocation() {
return location;
}
}
class Location {
public int distanceTo(Location other) {
...
}
}这样,定义位置(例如纬度、经度)所需的任何数据都完全包含在Location对象中。
https://stackoverflow.com/questions/33947892
复制相似问题