---------------------- android培训、java培训、期待与您交流!----------------------
面向对象的分析与设计
谁拥有数据,谁就对外提供操作这些数据的方法。
Lamp
类的编写
package com.itcast;
public enum Lamp {
S2N("N2S","S2W",false),S2W("N2S","S2W",false),
E2W("W2E","E2S",false),E2S("W2N","S2N",false),
S2E(null,null,true),E2N(null,null,true),
N2W(null,null,true),W2S(null,null,true),
N2S(null,null,false),N2E(null,null,false),
W2E(null,null,false),W2N(null,null,false);
private String opposite;
private boolean lighted;
private String next;
private Lamp(String opposite,String next,boolean lighted)
{
this.opposite=opposite;
this.next=next;
this.lighted=lighted;
}
public void light()
{
this.lighted=true;
if(opposite!=null)
{
Lamp.valueOf(opposite).light();
}
System.out.println(name()+"绿了");
}
public boolean isLighted()
{
return lighted;
}
public Lamp blackOut()
{
this.lighted=false;
if(opposite!=null)
{
Lamp lampOpposite =Lamp.valueOf(opposite);
lampOpposite.blackOut();
}
Lamp nextLamp =null;
if(next!=null)
{
nextLamp=Lamp.valueOf(next);
System.out.println("绿灯从"+name()+"----切换为"+next);
nextLamp.light();
}
return nextLamp;
}
}
l
LampController类的编写
lLampController构造方法中要设定第一个为绿的灯。
lLampController对象的start方法中将当前灯变绿,然后启动一个定时器,每隔10秒将当前灯变红和将下一个灯变绿。
public class LampController
{
private Lamp currentLamp ;
public LampController()
{
currentLamp =Lamp.S2N;
currentLamp.light();
ScheduledExecutorService timer = Executors.newScheduledThreadPool(1);
timer.scheduleAtFixedRate(
new Runnable()
{
public void run()
{
currentLamp = currentLamp.blackOut();
}
},
6,6,TimeUnit.SECONDS);
}
}
l
Road
类的编写
l每个Road对象都有一个name成员变量来代表方向,有一个vehicles成员变量来代表方向上的车辆集合。
l在Road对象的构造方法中启动一个线程每隔一个随机的时间向vehicles集合中增加一辆车(用一个“路线名_id”形式的字符串进行表示)。
l在Road对象的构造方法中启动一个定时器,每隔一秒检查该方向上的灯是否为绿,是则打印车辆集合和将集合中的第一辆车移除掉。
public class Road {
private List<String> vechicles = new ArrayList<String>();
private String name =null; ;
public Road (String name)
{
this.name = name;
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);
}
}
lMainClass类的编写
l用for循环创建出代表12条路线的对象。
l接着再获得LampController对象
public class MainClass {
/**
* @param args
*/
public static void main(String[] args)
{
String [] directions = new String[]{
"S2N","S2W","E2W","E2S","N2S","N2E","W2E","W2N","S2E","E2N","N2W","W2S"
};
for(int i=0;i<directions.length;i++){
new Road(directions[i]);
}
new LampController();
}
}
---------------------- android培训、java培训、期待与您交流! ----------------------
详细请查看:http://edu.youkuaiyun.com/heima