两块石头磨成一把石刀,石刀可以砍树,砍成木材,木材做椅子
张老师的形象比喻
StoneKnife = KnifeFactory.createKnife(stone)
Stone
material = StoneKnife.cut(tree)
tree
Chair = ChairFactory.makeChair(material)
material
chair
项目需求中写:应考虑左转车辆控制信号灯,右转车辆不受信号灯控制。
为了统一编程模型,把右拐弯的路上都看做是有一个绿灯,很关键
明确交通灯系统的对象模型:路(Road),灯(Lamp),灯控制器(LampController),车
12条路 (Road对象),看图:
S2N,S2W, E2W, E2S,N2S, N2E, W2E, W2N,S2E, E2N, N2W, W2S;
程序中用灯的名字来构造路,经典啊,Lamp.valueOf(Road.this.name)就能拥有这条路上的灯
String [] directions = new String[]{
"S2N","S2W","E2W","E2S","N2S","N2E","W2E","W2N","S2E","E2N","N2W","W2S"
};
for(int i=0;i
}
路中拥有车,路就提供增加和减少车辆的方法,车只是用一个String来表示的
Road.this.name + "_" + i
路看做一个容器List
private List
路上随即产生车辆
vechicles.add(Road.this.name + "_" + i);
需求中写车辆通过路口的时间为一秒,转化到程序里是这样的,
每隔一秒,就判断这条路上的灯,灯状态为true,然后移出路上的一辆车,
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);
每条路上对应一个灯,灯是固定的12个,所以想到用枚举,而且可以通过字符串就表示元素了Lamp.valueOf(name)
S2N("N2S", "S2W", false), S2W("N2E", "E2W", false), E2W("W2E", "E2S", false), E2S(
"W2N", "S2N", false),
N2S(null, null, false), N2E(null, null, false), W2E(null, null, false), W2N(
null, null, false),
S2E(null, null, true), E2N(null, null, true), N2W(null, null, true), W2S(
null, null, true);
灯里面有三变量
private boolean lighted;表示灯的亮与不亮
private String opposite;对应方向的灯
private String next; 下一个变亮的灯
只有四个灯需要opposite和next变量,四个灯对应方向的灯不需要,右拐弯的灯不需要
灯的点亮设计:把当前灯变量,再让自己对应方向的灯变量
this.lighted = true;
if (opposite != null)
{
Lamp.valueOf(opposite).light();
}
灯的熄灭设计:把当前灯熄灭,同时熄灭对应的灯,点亮对应的下一个灯,同时return下一个灯
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;
灯的控制器设计:
先从南到北的灯开始点绿
currentLamp = Lamp.S2N;
currentLamp.light();
每隔10秒将当前绿灯变为红灯,并让下一个方向的灯变绿
timer.scheduleAtFixedRate(new Runnable()
{
public void run()
{
System.out.println("来啊");
currentLamp = currentLamp.blackOut();
}
}, 10, 10, TimeUnit.SECONDS);
主程序设计,
String [] directions = new String[]{
"S2N","S2W","E2W","E2S","N2S","N2E","W2E","W2N","S2E","E2N","N2W","W2S"
};
for(int i=0;i
}
new LampController();
创建12条路,每条路上2个线程:随即产生车辆和判断灯的状态移动车,
创建灯控制器,点亮南到北的灯,整个系统运行拉。
交通灯系统是枚举的典型应用,我是这样认为的,通过该系统让我对
枚举的应用深刻理解了,谢谢老师啊。