通过 ID 引用对象? (Java)

Referring to Objects by an ID? (Java)

我不是 Java-新手,但我无法理解最近发生的问题。

我必须在 Java 中模拟道路系统。为了适当的 OOP,我有一辆 class 汽车和一条 class 街道(当然还有其他几条管理整个模拟 ^^)。我已经成功地模拟了一条道路上的拥堵并且没有遇到任何问题。

好的,问题来了:我想将我的模拟从一条孤独的街道扩展到一个道路系统。所以我想到了一个叫做 "RoadSystem" 的 class,它可能有一系列街道和某种连接(我想到了 'knots'),让汽车知道它们可以在哪里行驶到达他们行驶的街道尽头。

问题是我不知道如何实现这些结。汽车必须能够询问街道 "hey bro, I'm at the end of you, where can I drive now?" 并且街道应该以某种方式知道哪个结引用了它,并向它询问也连接到这个特定结的街道。我如何做这个参考? 我想到了一个 ID,但是如果街道必须搜索每个节点的街道 ID 以便在那里找到自己的 ID,那么对于更大的道路系统来说这可能会变得非常慢。还是我缺少解决问题的明显方法?

非常感谢您的帮助!

来自德国的问候,

拉菲

你应该看看 LinkedList 的源代码,也许可以适应这个原则。一条道路有 2 个连接点,而一个交叉路口可能有 2 到 4 个?

Abstract class RoadElement{
  //abstract for simulation purpose, maybe randomized
  //calculation of next direction, etc.
}

class Road extends RoadElement{
  private RoadElement previous = null;
  private RoadElement next = null;
}

class Intersection extends RoadElement{
    private RoadElement northernConnection = null;
    private RoadElement easternConnection = null;
    private RoadElement southernConnection = null;
    private RoadElement westernConnection = null;
}

最后,您可以根据需要设计路网并连接 RoadElements。在模拟过程中,您不必关心具体实例,因为它们将在逻辑上连接。

(您稍后可以使用其他 RoadElements 来改进这一点,例如 "Curves" 限速、人行横道与停车时间等)

示例:

   List<RoadElement> RoadMap = new LinkedList<RoadElement>();
   Road r1 = new Road();
   Intersection i1 = new Intersection();
   r1.setPrevious(i1);
   i1.setNorthernConnection(r1);
   ....

然后,在模拟过程中,您可以执行以下操作:

Car currentCar = getCurrentCar();
RoadElement re = currentCar.getLocation();
if (re instanceof Road){
  //can we drive "forward and backward?"
  if ((Road)re).getPrevious() != null){

  }

  if ((Road)re).getNext() != null){

  }
}else if (re instanceof Intersection){
   //check available outgoing roads
   if ((Intersection)re).getNorthernConnection() != null){

   }
   ...
}