你应该看看 SourceCodeLinkedList
并且也许适应这个原则。一条道路有 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 来改进这一点,例如速度有限的“曲线”、带有停车时间的人行横道等)
例子:
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){
}
...
}