经典面试项目--交通灯管理系统(二)
boolean lighted = Lamp.valueOf(Road.this.name).isLighted();
if(lighted){
System.out.println(vechicles.remove(0) + " 驶过路口!");
}
}
}
}, //要执行的任务
1, //首次执行的延迟时间
1, //两次操作之间的时间差
TimeUnit.SECONDS //设定时间的单位为秒
);
}
}
Lamp类,
1,固定十二条线路所以有对应的十二个Lamp实例,上面分析得到只需要控制其中的四条线路即可。
2,每个灯都有状态显示,绿(true)和红(false),并且一条线路上的灯变红或者变绿之后其对向线路上的灯要与之同步,下一条线路上的灯也要随之作出反应变为绿灯。
3,由于直行和左转绿灯时间不同,所以还需要引入方向(Direction)接口并增加一个属性direction表示灯所在路线的方向
[java]
public interface Direction {
/*表示路线的行驶方法,有三个值,如下*/
public static final int LEFT = -1;
public static final int CENTER = 0;
public static final int RIGHT = 1;
int getDirection();
}
[java]
import java.util.Date;
enum Lamp implements Direction {
//每个枚举元素各表示一个方向的控制灯
S2N("N2S", "S2W", CENTER, false), S2W("N2E", "E2W", LEFT, false), E2W("W2E", "E2S", CENTER, false), E2S("W2N", "S2N", LEFT, false),
// 与上面声明的四个方向的灯一一对应,被动执行即可
N2S(null, null, CENTER, false), N2E(null, null, LEFT, false), W2E(null, null, CENTER, false), W2N(null, null, LEFT, false),
// 右转信号灯常亮为绿灯
S2E(null, null, RIGHT, true), E2N(null, null, RIGHT, true), N2W(null, null, RIGHT, true), W2S(null, null, RIGHT, true);
private String opposite; //表示对向路线的灯
private String next; //表示下一条路线的灯
private boolean lighted; //灯的状态
private int direction; //表示灯所在路线的方向,可能为LEFT\CENTER\RIGHT
private Lamp(String opposite, String next,int direction, boolean lighted){
this.opposite = opposite;
this.next = next;
this.direction = direction;
this.lighted = lighted;
}
public boolean isLighted(){
return lighted; //判断灯的状态,变亮表示绿灯,变黑表示红灯
}
public int getDirection() { //获取灯所在路线的方向
return direction;
}
// 将当前灯变为绿灯,同时其对向的灯一起随之改变
public void light(){
this.lighted = true;
if(opposite != null){
Lamp.valueOf(opposite).light();
}
System.out.println(name() + " 绿灯亮了,下面总共应该有6个方向能看到汽车穿过!");
}
// 将当前灯和对应方向的灯变成红灯,并且下一条路线上的灯变绿,返回这个变绿的灯
public Lamp blackOut(){
this.lighted = false;
if(opposite != null){
Lamp.valueOf(opposite).blackOut();
}
Lamp nextLamp = null;
if(next != null){
nextLamp = Lamp.valueOf(next);
nextLamp.light();
System.out.println("绿灯从" + name() + "-------->切换为" + next);
System.out.println("Time :" + new Date());
}
return nextLamp;
}
}
LampController类,
1, 整个
系统中只需要一个交通灯控制器即可,所以,这个类应该设计为单例。
2, 运行时需要指定第一个为绿的灯,所以在构造方法中指定最好。
3, 实现两个定时器分别控制直行和左转的灯,直行绿灯时间20秒,左转绿灯时间15秒
[java]
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
class LampController {
//表示当前灯
private Lamp currentLamp;
public LampController(){
//指定由南向北的灯首先为绿灯