你應該看看的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