您的位置:首页 > 职场人生

黑马程序员-交通灯管理系统学习笔记

2012-04-11 09:44 567 查看
---------------------- android培训java培训、期待与您交流! --------------------

谁拥有数据,谁就拥有对外提供操作这些数据的方法。刚开始还没提怎么理解,听老师说的人在黑板上画圆,就很开朗了,画圆,需要半径,半径,这些都是数据,圆拥有这些数据,所以画圆的方法是圆提供的,人只是在调用画圆这个方法而已。

理解 如何抽象出对象的几个例子:

1.人在黑板上画圆

包含对象,Person Blackboard Circle

画圆的方法,应该是Circle提供的,因为圆心,半径都是Circle的属性。

而人在黑板上花园,只是调用了Circle的方法而已。

2.列车司机刹车

刹车的方法应该是列车的方法,列车司机调用了列车的刹车方法。

3.小球从绳子的一端移动到另一端

class Rope{

private Point start;

private Point end;

public Rope(Point start,Point end){

this.start = start;

this.end = end;

}

public Point nextPoint(Point currentPoint){

//....

}

}

class Ball{

private Rope rope;

private Point currentPoint;

public Ball(Rope rope,startPoint){

this.rope=rope;

this.currentPoint = startPoint;

}

public void move(){

currentPoint = rope.nextPoint(currentPoint);

}

}

灯类用枚举来创建,这样可以控制不让别人创建新的灯,只能用定义的12个灯。

Car

public class Car {

Dir wantedDir;

Dir nowDir;

int id;

public Car(int id,Dir nowDir,Dir wantedDir) {

this.nowDir = nowDir;

this.wantedDir = wantedDir;

}

public void run() {System.out.println("车" + id + "开走");}

}

Controller

import java.util.ArrayList;

import java.util.List;

import java.util.Random;

public class Controller {

private Light light = null;

private Dir dir = null;

private List<Car> cars = new ArrayList<Car>();

Random random = new Random();

public void haveCars() {

Dir nowDir = null;

Dir wantedDir = null;

for(int i = 0;i < 50;i++) {

int j = random.nextInt(4);

nowDir = Dir.values()[j];

int k = random.nextInt(4);

if(k-j != 2 && k-j != -2) {

wantedDir = Dir.values()[k];

}else {

wantedDir = Dir.values()[j+1];//如果想倒车让它先向右拐。因为Dir中是按顺时针定义的,所以在

//原方向上+1即可

}

Car c = new Car(i,nowDir,wantedDir);

cars.add(c);

}

}

public void start() {

//haveCars();

//其实这里不用while(true)应该在下面使用随机数控制是否产生车辆

while(true) {

//在这个条件下产生车辆

int i = random.nextInt(30);

if(i > 25) {

haveCars();

}

dir = light.changeLight();

carRunnable(dir);

}

}

public void carRunnable(Dir dir) {

for(Car c : cars) {

if(c.wantedDir == dir && c.nowDir == dir) {

c.run();

cars.remove(c);

}

if(c.wantedDir == dir && c.nowDir != dir) {

c.run();

cars.remove(c);

}

}

}

}

Light类

public class Light {
private static int i = 0;
private boolean East = false;
private boolean South = false;
private boolean West = false;
private boolean North = false;

public Dir changeLight() {
i = (i + 1) % 4;
switch(i) {
case 0 :
East = true;
South = false;
West = false;
North = false;
return Dir.E;

}
try {
Thread.sleep(30000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}

---------------------- android培训java培训、期待与您交流! ----------------------
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: