对交通灯管理系统车辆行驶路线的理解:
总共12条路线,由于车辆是靠着马路右侧行驶,所以右转弯的4条路线的控制灯可以假设称为常绿状态,另外,其他的8条线路是两两成对的,可以归为4组,4组灯是同时变绿和变红,在当前绿灯变红时当前灯的下一个方向上的灯变绿。
对象分析与代码实现:谁拥有数据,谁就对外提供操作这些数据的方法。
总共有3个对象,(1)交通灯Lamp,12个方向上的每个交通灯都维护一个状态:亮(绿)或不亮(红),每个交通灯要有变亮和变黑的方法,并且能返回自己的亮黑状态。
首先要有判断当前灯是否为亮(绿)的方法:
public boolean isLighted(){
retrun lighted;
}
再有就是对应方向上的灯同时变亮(绿)的方法:
public void light(){
this.lighted = true;
if(opposite != null){
Lamp.valueOf(opposite).light();
}
System.out.println(name() + " lamp is green,下面总共应该有6个方向能看到汽车穿过!");
}
最后就是对应方向上的灯同时变黑(红)的方法,这里设计的让此方法返回下一个灯。
public Lamp blackOut(){
this.lighted = false;
if(opposite != null){
Lamp.valueOf(opposite).blackOut();
}
Lamp nextLamp= null;
if(next != null){
nextLamp = Lamp.valueOf(next);
System.out.println("绿灯从" + name() + "-------->切换为" + next);
nextLamp.light();
}
return nextLamp;
}
}
交通灯类的编写在java高新技术中带有抽象方法的枚举时已经写过
(2)交通灯控制系统LampController,LampController构造方法中要设定第一个为绿的灯。
currentLamp = Lamp.S2N; //刚开始让由南向北的灯变绿;
currentLamp.light();
LampController对象的start方法中将当前灯变绿,然后启动一个定时器,每隔10秒将当前灯变红和将下一个灯变绿。
/*每隔10秒将当前绿灯变为红灯,并让下一个方向的灯变绿*/
ScheduledExecutorService timer = Executors.newScheduledThreadPool(1);
timer.scheduleAtFixedRate(
new Runnable(){
public void run(){
System.out.println("来啊");
currentLamp = currentLamp.blackOut();
}
},
10,
10,
TimeUnit.SECONDS);
}
(3)路Road,路中存储着车辆的集合,显然路上就应该有增加车辆和减少车辆的方法了。
//模拟车辆不断随机上路的过程
ExecutorService pool = Executors.newSingleThreadExecutor();
pool.execute(new Runnable(){
public void run(){
for(int i=1;i<1000;i++){
try {
Thread.sleep((new Random().nextInt(10) + 1) * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
vechicles.add(Road.this.name + "_" + i);
}
}
});
//每隔一秒检查对应的灯是否为绿,是则放行一辆车
ScheduledExecutorService timer = Executors.newScheduledThreadPool(1);
timer.scheduleAtFixedRate(
new Runnable(){
public void run(){
if(vechicles.size()>0){
boolean lighted = Lamp.valueOf(Road.this.name).isLighted();
if(lighted){
System.out.println(vechicles.remove(0) + " is traversing !");
}
}
}
},
1,
1,
TimeUnit.SECONDS);
}