2015-06-04 67 views
1

我不是Java-Newbie,但我无法解决最近发生的问题。通过ID引用对象? (Java)

我必须模拟Java中的道路系统。为了适当的面向对象,我有一个班车和一个班级街道(和其他几个人来管理整个模拟课程^^)。我已经设法模拟一条路上的堵塞,并且没有问题。

好的,问题来了:我想将我的模拟从一个孤独的街道延伸到一个道路系统。所以我想到了一个类似“RoadSystem”的课程,它可能有一系列街道和某种连接(我想到了“节点”),让汽车知道他们到达街道尽头时可以驾驶的位置驾驶。

问题是我不知道如何实现这些结。汽车必须能够问街道:“嗨,兄弟,我在你的尽头,我现在可以在哪里开车?”并且街道应该知道哪个结有一个参考,并且要求它连接到这个特定结的街道上。我该如何做这个参考? 我想到了一个身份证,但是如果街道必须搜索每个结的街道ID才能在那里找到自己的ID,那么对于较大的道路系统,这可能会变得非常缓慢。或者我错过了我的问题的明显解决方案?

每个帮助高度赞赏!来自德国

问候,

Ruffy

+0

最终的答案取决于你想要放入模拟的细节。是否必须考虑车道方向并在交叉口(等)上穿越车辆? 或者是一个从道路到道路“切换”的抽象事物? – dognose

+1

街道(和它们的交点)可以模拟为GRAPH http://introcs.cs.princeton.edu/java/45graph/ – Hector

+0

看这个SO回答http://stackoverflow.com/questions/51574/good-java -graph-algorithm-library – Hector

回答

0

你应该看看的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; 
} 

最后,您可以设计您的道路网络并将道路要素链接为需要的。在模拟过程中,您不必关心具体的instaces,因为它们将被逻辑连接起来。

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

然后,在:

实施例(你可以稍后用额外RoadElements,如“曲线”具有有限速度,人交点与停止时间等改善此)模拟,你可以做类似的事情:

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

    } 
    ... 
} 
+0

感谢您的回答。帮助过我! :) –

+0

@RuffyxNami欢迎您。 – dognose

+0

如何实现Car.getLocation方法?我不需要代码,只是想法.. –