---
title: "黑马程序员——交通灯管理系统"
author: "把阳光剪成雨Java"
date: "2012-11-20T10:28:29Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2012-11-23T19:25:54Z"
id: 1730409
url: "https://gekui.iteye.com/blog/1730409"
---

**----------------- [android培训](http://www.itheima.com)、[java培训](http://www.itheima.com)、期待与您交流！ -----------------**

**交通灯管理系统**

1，根据交通灯路线的基本思想，绘出下图。共12条路线。

    

  ![交通灯管理系统](http://dl.iteye.com/upload/attachment/0076/8222/2bd65b9a-d81d-3aff-8a15-ea84083f3a5b.jpg)

面向对象设计要把握的一个重要的经验：**谁拥有数据，谁就对外提供操作这些数据的方法。**再牢牢掌握几个典型的案例就可以：1.人在黑板上画圆（画圆方法是圆上的方法）2列车司机急刹车（急刹车是车的方法）3.售货员统计收获小票的金额（统计是小票上的方法）4你把门关上了（关门是门上的方法）。

搞清面向对象的设计思想：

（1），球从绳子的一端移到另一端

**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){

       **return** **null**;

    }

}

**class** Ball{

    **private** Rope rope;

    **private** Point currentPoint;

    **public** Ball(Rope rope,Point currentPoint){

       **this**.rope = rope;

       **this**.currentPoint = currentPoint;

    }

    **public** **void** move(){

       rope.nextPoint(currentPoint);

    }

}

（2）  ，两块石头磨成一把刀，石刀可以砍树，砍成木材，木材可以做出椅子。

//两块石头磨成一把刀，石刀可以砍树，砍成木材，木材可以做出椅子。

/\*Stone

   StoneKnife sk = StoneFactory.createKnife(Stone fist,Stone second);

StoneKnife

   Material m = sk.cut(tree);

Tree

Material

   Chair c = ChairFactory.createChair(m);

Chair

\*/

 

2，Road

package com.isoftstone.interview.traffic;

 

import java.util.ArrayList;

import java.util.List;

import java.util.Random;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import java.util.concurrent.ScheduledExecutorService;

import java.util.concurrent.TimeUnit;

 

/\**

 * 每个Road对象代表一条路线，总共有12条路线，即系统中总共要产生12个Road实例对象。

 * 每条路线上随机增加新的车辆，增加到一个集合中保存。

 * 每条路线每隔一秒都会检查控制本路线的灯是否为绿，是则将本路线保存车的集合中的第一辆车移除，即表示车穿过了路口。

 * @author 张孝祥 www.it315.org

 *

 \*/

public class Road {

    private List&lt;String&gt; vechicles = new ArrayList&lt;String&gt;();

   

    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&lt;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()&gt;0){

                         boolean lighted = Lamp.valueOf(Road.this.name).isLighted();

                         if(lighted){

                            System.out.println(vechicles.remove(0) + " is traversing !");

                         }

                     }

                    

                  }

              },

              1,

              1,

              TimeUnit.SECONDS);

      

    }

}

3,Lamp

**package** com.isoftstone.interview.traffic;

 

/\**

 * 每个Lamp元素代表一个方向上的灯，总共有12个方向，所有总共有12个Lamp元素。

 * 有如下一些方向上的灯,每两个形成一组，一组灯同时变绿或变红，所以，

 * 程序代码只需要控制每组灯中的一个灯即可：

 * s2n,n2s   

 * s2w,n2e

 * e2w,w2e

 * e2s,w2n

 * s2e,n2w

 * e2n,w2s

 * 上面最后两行的灯是虚拟的，由于从南向东和从西向北、以及它们的对应方向不受红绿灯的控制，

 * 所以，可以假想它们总是绿灯。

  \*/

/\*\*/

 

**public** **enum** Lamp {

    /\*每个枚举元素各表示一个方向的控制灯\*/  

  *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** Lamp(String opposite,String next,**boolean** lighted){

       **this**.opposite = opposite;

       **this**.next = next;

       **this**.lighted = lighted;

    }

 

 

    /\*当前灯是否为绿\*/ 

    **private** **boolean** lighted;

    /\*与当前灯同时为绿的对应方向\*/  

    **private** String opposite;

    /\*当前灯变红时下一个变绿的灯\*/  

    **private** String next;

    **public** **boolean** isLighted(){

       **return** lighted;

    }

   

    /\**

     * 某个灯变绿时，它对应方向的灯也要变绿

     \*/

    **public** **void** light(){

       **this**.lighted = **true**;

       **if**(opposite != **null**){

           Lamp.*valueOf*(opposite).light();

       }

       System.*out*.println(name() + " lamp is green，下面总共应该有6个方向能看到汽车穿过！");

      

    }

   

    /\**

     * 某个灯变红时，对应方向的灯也要变红，并且下一个方向的灯要变绿

     * **@return** 下一个要变绿的灯

     \*/

    **public** Lamp blackOut(){

       **this**.lighted = **false**;

       **if**(opposite != **null**){

           Lamp.*valueOf*(opposite).blackOut();

       }     

      

       Lamp nextLamp= **null**;

       **if**(next != **null**){

           nextLamp = Lamp.*valueOf*(next);

           System.*out*.println("绿灯从" + name() + "--------&gt;切换为" + next);      

           nextLamp.light();

       }

       **return** nextLamp;

    }

}

 

4,LampController

package com.isoftstone.interview.traffic;

 

import java.util.concurrent.Executors;

import java.util.concurrent.ScheduledExecutorService;

import java.util.concurrent.TimeUnit;

 

public class LampController {

    private Lamp currentLamp;

   

    public LampController(){

       //刚开始让由南向北的灯变绿;    

       currentLamp = Lamp.S2N;

       currentLamp.light();

      

       /\*每隔10秒将当前绿灯变为红灯,并让下一个方向的灯变绿\*/     

       ScheduledExecutorService timer =  Executors.newScheduledThreadPool(1);

       timer.scheduleAtFixedRate(

              new Runnable(){

                  public  void run(){

                     System.out.println("来啊");

                     currentLamp = currentLamp.blackOut();

              }

              },

              10,

              10,

              TimeUnit.SECONDS);

    }

}

5,MainClass

**package** com.isoftstone.interview.traffic;

 

**public** **class** MainClass {

 

    /\**

     * **@param** args

     \*/

    **public** **static** **void** main(String\[] args) {

      

       /\*产生12个方向的路线\*/     

       String \[] directions = **new** String\[]{

              "S2N","S2W","E2W","E2S","N2S","N2E","W2E","W2N","S2E","E2N","N2W","W2S"     

       };

       **for**(**int** i=0;i&lt;directions.length;i++){

           **new** Road(directions\[i]);

       }

      

       /\*产生整个交通灯系统\*/     

       **new** LampController();

    }

 

}

 

总结：张老师的这个视频不仅仅是交通管理系统，它主要强调是一种编程思想。

1，思维清晰的描述出项目的整个流程，甚至每一个细节。

2，采用面向对象的思想对1中的描述进行归纳。

3，代码实现现实模型。