简体   繁体   English

两个物体之间的关系

[英]Relationship between two objects

I'm working on a project for school that is challenging my understanding of OOP. 我正在为一个学校项目工作,这对我对OOP的理解提出了挑战。 I have multiple objects of the same class, City. 我有同一个班级的多个对象,城市。 Each City has a location. 每个城市都有一个位置。 If my understanding is correct, since the distance between each City is dependent on another City "int distance" can't be a field within the class City. 如果我的理解是正确的,则由于每个城市之间的距离取决于另一个城市,因此“ int distance”不能是“城市”类中的一个字段。 I can write a method to calculate the distance between each City, but I'm not sure how/where to save that data. 我可以编写一种方法来计算每个城市之间的距离,但不确定如何/在何处保存该数据。 I would like to eventually sort this data to find which City objects are in closest proximity. 我想最终对这些数据进行排序,以找到最接近的City对象。

I would suggest a Map class (as in cartography, not the usual Collection ), whose instances would contain a Set of Cities . 我建议使用Map类(例如在制图学中,而不是通常的Collection ),其实例将包含Set of Cities They could provide method to calculate additional information about the relations between their Cities , and cache the result if needed. 他们可以提供方法来计算有关其Cities之间关系的其他信息,并在需要时缓存结果。

It is not necessary that the Map contains the Cities but it sounds logical and will surely help manipulating them. Map不必包含Cities但听起来很合逻辑,并且一定会帮助您进行操作。 If you don't want that you could use a "helper class", something like DistancesHelper , defining static methods to work on Cities that could interact with a static cache. 如果您不希望使用“ helper类”,例如DistancesHelper ,则定义静态方法以在可以与静态缓存进行交互的Cities上工作。

It seems to me that calculation of distance should be a method of Location not a method of City . 在我看来,距离的计算应该是Location的方法而不是City的方法。 You could later decide your map has other points of interest besides cities which also have a location. 稍后您可以确定地图上除了具有位置的城市以外,还有其他景点。

So my suggestion of structure would be: 所以我对结构的建议是:

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) {
        ...
    }
}

That way any data required to define location (eg latitude, longitude) is completely contained within the Location object. 这样,定义位置所需的任何数据(例如,纬度,经度)都完全包含在Location对象中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM