Dark Horse programmer: Traffic Light Management System

Source: Internet
Author: User

---------- Android training, Java training, and hope to communicate with you!
----------

Business Requirements

The traffic light management system logic at the intersection is simulated. The specific requirements are as follows:

Asynchronously and randomly generate vehicles traveling along each route.

For example:

Vehicles from south to north-direct vehicles

Vehicles going from West to south-turn right

Vehicles from the east to the south-turn vehicles

...

1. Ignore the yellow light. Only the red light and the green light are considered.

2. Control Signals for left-turn vehicles should be considered. Vehicles that turn right should not be controlled by traffic signals.

3. The specific traffic light control logic is the same as the common traffic light control logic in real life, regardless of the control logic in special circumstances.

Note: vehicles in the North-South direction and vehicles in the east-west direction are allowed to interchangeably. vehicles in the same direction should be allowed to go directly and then turn left.

4. The time for each vehicle to pass through the intersection is 1 second (Note: simulation can be performed through thread sleep ).

5. You can set the random generation interval and traffic light switching interval.

6. You do not need to implement the GUI. You only need to implement the system logic. You can use the LOG method to display the program running results.

Business analysis cannot be a fantasy, so you must draw pictures.

There are a total of 12 routes. to unify the programming model, we can assume that each route has a traffic light to control it. The control lights of the four routes in the right turn can be assumed to be evergreen, in addition, the other eight lines are paired with each other and can be classified into four groups. Therefore, the program only needs to consider the switching sequence of the control lights marked with the four routes of the number in the figure, the control lights of the four routes in the opposite direction follow these four routes and do not need to be considered.

Object-Oriented Analysis and Design

We initially figured out which objects were: traffic lights, traffic light control systems, cars, and routes. When the car sees that the light corresponding to its route is green, it passes through the intersection? No, you still need to check whether there is a car in front of it and whether there is a car in front of it. Which object should you ask? The road stores a collection of vehicles. Obviously there should be ways to increase or decrease vehicles on the road. Let's look at the questions again. Here we don't want to reflect the process of moving a vehicle. We just capture the process of moving a vehicle through the intersection, that is, the process of capturing a car on the road, this car does not need to be designed as an object separately. It can be expressed as a string.

Multiple vehicles will appear on each route. New vehicles should be randomly added on the route, and a car should be reduced every second during the light-green period. Design a road class to represent a route. Each road object represents a route. There are 12 routes in total, that is, a total of 12 road instance objects will be generated in the system. A new vehicle is randomly added to each route and saved in a collection. Every second, each route checks whether the lights that control the current route are green. If yes, the first car in the car's set stored in the current route is removed, indicating that the car passes through the intersection. Every second of each route checks whether the light that controls the current route is green. When a light changes from green to red, the light in the next direction should be green. Design a lamp class to represent a traffic light. Each traffic light maintains a state: Bright (green) or not bright (RED). Each traffic light must have a method of changing from Bright to black, and can return their own bright black state. There are 12 routes in total, so a total of 12 traffic lights are generated in the system. The route of the right turn is not controlled by the light, but in order to let the program adopt a unified processing method, it is assumed that there are four right turn lights, but these lights are always on, that is, it never changes. In addition to the lights of the other eight routes in the right turn direction, they are paired and can be classified into four groups. Therefore, during programming, as long as one lamp is taken from each of the four groups, the four lights are turned on in round-robin mode, and the lights corresponding to the four lights change with each other, therefore, there must be a variable in the lamp class to remember the lights in the opposite direction. In the method of brightening and blackening a lamp object, the lights in the corresponding direction are also brightened and dimmed. When the light turns black, it is followed by the light of the next light, and a variable is used in the lamp class to remember its next light. No matter where the program gets the lights in a certain direction, each time it gets the same instance object, it is very convenient for the lamp class to use enumeration, there are always only instance objects that represent the lights in 12 directions. Design a lampcontroller class, which regularly turns the current green light red. Program source code

Rood

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;/*** each road object represents a route. There are 12 routes in total, that is, a total of 12 road instance objects are generated in the system. * A new vehicle is randomly added to each route and added to a collection for saving. * Every second of each route, the system checks whether the lights on the current route are green. If yes, the first car in the set of vehicles stored in the current route is removed, indicating that the car passes through the intersection. * @ Author Zhang Xiaoxiang www.it315.org **/public class road {private list <string> vechicles = new arraylist <string> (); Private string name = NULL; public road (string name) {This. name = Name; // simulate the process of random vehicles on the road executorservice pool = executors.newsinglethreadexecutor(registry.pool.exe cute (New runnable () {public void run () {for (INT I = 1; I <1000; I ++) {try {thread. sleep (new random (). nextint (10) + 1) * 1000);} catch (interruptedexc Eption e) {e. printstacktrace ();} vechicles. add (Road. this. name + "_" + I) ;}}); // check whether the corresponding lamp is green every second. If yes, release a car 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 );}}

Lamp

Package com. isoftstone. Interview. Traffic;/*** each lamp element represents a lamp in one direction, with 12 directions in total and 12 lamp elements in total. * There are lights in the following directions, each of which forms a group, and a group of lights turn green or red at the same time. Therefore, * the program code only needs to control one of the lights in each group: * s2n, n2s * s2w, n2e * e2w, w2e * e2s, w2n * s2e, n2w * e2n, w2s * The lights on the last two lines are virtual, since the south to the east and the west to the north, and their corresponding directions are not controlled by traffic lights, * We can assume that they are always green lights. * @ Author Zhang Xiaoxiang www.it315.org ** // **/Public Enum lamp {/* Each enumeration element represents a direction control lamp */s2n ("N2s", "s2w ", false), s2w ("n2e", "e2w", false), e2w ("w2e", "e2s", false), e2s ("w2n", "s2n ", false),/* the following elements indicate the lights in the opposite direction of the above elements. Their "Opposite Direction lights" and "next lights" should be ignored! */N2s (null, null, false), n2e (null, null, false), w2e (null, null, false), w2n (null, null, false ), /* right turns from the south to the east and from the west to the north are not controlled by traffic lights. Therefore, we can assume that they are always green lights */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;}/* whether the current light is green */private Boolean lighted;/* The direction corresponding to the green light at the same time */private string OPP Osite;/* The next green light when the current light turns red */private string next; Public Boolean islighted () {return lighted;}/*** when a light turns green, the light in the corresponding direction must also turn green */Public void light () {This. lighted = true; If (opposite! = NULL) {lamp. valueof (opposite ). light ();} system. out. println (name () + "lamp is green, there should be a total of 6 directions to see the car pass! ");}/*** When a light turns red, the light turns red in the corresponding direction, and the lights in the next direction need to turn green * @ return next the lights to turn green */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 ("green light from" + name () + "--------> switch to" + next); nextlamp. light () ;}return nextlamp ;}}

Lampcontrocller

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 () {// green the lampcontroller from south to north at the beginning; currentlamp = lamp. s2n; currentlamp. light ();/* change the current green light to a red light every 10 seconds and change the light in the next direction to green */scheduledexecutorservice timer = executors. newscheduledthreadpool (1); timer. scheduleatfixedrate (New runnable () {public void run () {system. out. println ("come on"); currentlamp = currentlamp. blackout () ;}}, 10, 10, timeunit. seconds );}}

Mainclass

Package COM. isoftstone. interview. traffic; public class mainclass {/*** @ Param ARGs */public static void main (string [] ARGs) {/* generate 12 directions */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]);}/* generate the entire traffic light system */New lampcontroller ();}}
Object-oriented

Object-Oriented Design has an important experience: anyone who owns the data provides external methods to operate the data.

Then you can grasp several typical cases: people draw circles on the blackboard, train drivers brake urgently, sales staff collect the amount of small tickets, and you close the door.

The two object-oriented interview questions of students are designed in an object-oriented manner as follows.

"Two stones are ground into a stone knife, which can cut trees, cut into wood, and make wood into chairs"

StoneKnife = StoneFactory.create(Stone first,Stone second)StoneStoneKnifeWood = StoneKnife.cut(Tree)TreeChair = WoodFactory.makeChair(wood)WoodChair

"The ball moves from a piece of rope to the other end"

Class rope {private point start; private point end; rope (point start, Point End) {This. start = start; this. end = end;} public point nextpoint (point currentpoint) {/*** the next point of the current point can be calculated using the mathematical formula of the 2.1 line, this detail is not a problem to be considered in the design phase * but the current vertex is the end vertex, null is returned. If the current vertex is not an online vertex, an exception is thrown */} class ball {private rope; private point currentpoint; Public ball (rope; point currentpoint) {This. rope = rope; this. currentpoint = currentpoint;} public void move () {currentpoint = rope. nextpoint (currentpoint); system. out. println ("Move the ball to" + currentpoint );}}

 

---------- Android training, Java training, and hope to communicate with you!
----------

See http://edu.csdn.net/heima/ for details

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.