你应该看看的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){
}
...
}
最终的答案取决于你想要放入模拟的细节。是否必须考虑车道方向并在交叉口(等)上穿越车辆? 或者是一个从道路到道路“切换”的抽象事物? – dognose
街道(和它们的交点)可以模拟为GRAPH http://introcs.cs.princeton.edu/java/45graph/ – Hector
看这个SO回答http://stackoverflow.com/questions/51574/good-java -graph-algorithm-library – Hector