第一种:传统的方法
public abstract class TrfficLight {
private int time;
public final static TrfficLight RED = new TrfficLight(30) {
@Override
public TrfficLight nextLight() {
return GREEN;
}
};
public final static TrfficLight YELLOW = new TrfficLight(5) {
@Override
public TrfficLight nextLight() {
return RED;
}
};
public final static TrfficLight GREEN = new TrfficLight(45) {
@Override
public TrfficLight nextLight() {
return YELLOW;
}
};
public abstract TrfficLight nextLight();
public TrfficLight(int time) {
this.time = time;
}
public int getTime() {
return time;
}
@Override
public String toString() {
if (this==RED){
return "GREEN";
}else if(this==YELLOW){
return "RED";
}else{
return "YELLOW";
}
}
}
第二种:枚举的方法
public enum TrifficLinghtEnum {
RED(30){
@Override
public String nextLight() {
return "GREEN";
}
},
YELLOW(5){
@Override
public String nextLight() {
return "RED";
}
},
GREEM(45){
@Override
public String nextLight() {
return "YELLOW";
}
};
public abstract String nextLight();
private int time;
private TrifficLinghtEnum(int time) {
this.time=time;
}
public int getTime() {
return time;
}
}
现在我们定义一个类来测试以下,结果是不是一样的呢?
public class TrfficTest {
public static void main(String[] args) {
/*
* 传统的方法
*/
TrfficLight t1=TrfficLight.GREEN;
System.out.println(t1.nextLight()+"->wait:"+t1.getTime());
TrfficLight t2=TrfficLight.RED;
System.out.println(t2.nextLight()+"->wait:"+t2.getTime());
TrfficLight t3=TrfficLight.YELLOW;
System.out.println(t3.nextLight()+"->wait:"+t3.getTime());
System.out.println("----------华丽的分割线-------------");
/*
* ,枚举的方法
*/
TrifficLinghtEnum tle1=TrifficLinghtEnum.GREEM;
System.out.println(tle1.nextLight()+"->wait:"+tle1.getTime());
TrifficLinghtEnum tle2=TrifficLinghtEnum.RED;
System.out.println(tle2.nextLight()+"->wait:"+tle2.getTime());
TrifficLinghtEnum tle3=TrifficLinghtEnum.YELLOW;
System.out.println(tle3.nextLight()+"->wait"+tle3.getTime());
}
}
打印结果为:
|
|