GofPatterns GofPatterns


Structural Patterns  «Prev  Next»

Backed up Vehicles Intersection - Exercise

Objective: Write a class that contains the vehicles currently backed up at the intersection.
The next piece of the traffic flow system is to write a class that creates the vehicle queues at the intersection. This class should be named VehicleQueue. One VehicleQueue class should be sufficient with different instances for different directions. The basic structure of the class is shown in this diagram:

UML diagram containing the VehicleQueue class.

The theFactory attribute is the creator class that is responsible for creating individual vehicles. It decides what the likelihood is of a particular vehicle appearing in this queue. The vehiclesPerSecond attribute is a floating point number between 0 and 1. It determines the likelihood that a vehicle (of any type) appears in this queue in any given second. The enter() method is called each second. The leave() method is invoked whenever the corresponding light is green.
As well as the attributes and operations documented here, you will need to provide a means of storing and manipulating the list of cars.
In Java 1.1 the Vector class is useful, though not terribly efficient for this purpose. In Java 1.2 the LinkedList class is a much safer bet. In C++, the standard templates library can be helpful. I have deliberately left the type of the Queue unspecified so you can use whatever is convenient in your environment.
Each Queue object knows the chance of a vehicle entering the queue at an arbitrary time slice. Each queue is further parameterized with a VehicleFactory object that understands the chances of the different vehicles entering the queue at any time. When the enter() method is invoked, a random number function is called to determine whether or not to add a new vehicle to the queue. When the light turns green, the leave() method is invoked as many times as possible. We are not quite ready, yet, however, to actually invoke the queuing functions. That will have to wait for the Timer class and Observer pattern used later in the course.
  1. The getLength() method returns the total length in meters of the queue; that is the sum of the lengths of the individual vehicles.
  2. The getSize() method, by contrast, returns the number of vehicles in the queue. Finally, list() is a method intended mostly for debugging that prints the list of vehicles in the queue on the console.

Type your answer in the text area below.
Click the Submit button to see the result.