Class 2 | Intermediate Java 30-IT-397 |
Singleton Example
/*
* Road.java
*
* Created on April 2, 2002, 8:38 PM
*/
package singleton;
/**
*
* @author default
*/
public class Road {
// Max capacity for this road.
int capacity = 5;
// The Array will hold our car objects.
Car[] cars = new Car[capacity];
// number of cars currently on the road.
int carCount = 0;
// This is an instance of the singleton Road
object.
static Road road = null;
/** Creates a new instance of Road. This
is private, and can only be called by the Road class itself. */
private Road() {
}
/***
* get an instance of the Road singleton.
*
*/
public static Road roadInstance() {
// Pardon my use of
an if test.
if (road == null) {
// Call the constructor internally.
road = new Road();
}
// Return the road singleton.
return road;
}
/**
* Add a car to the road.
*
* @param car the car to add.
*/
public void addCar(Car car) throws ArrayIndexOutOfBoundsException
{
// Note that, if we
exceed capacity, the method will automatically throw an exception.
cars[carCount] = car;
carCount++;
System.out.println("Car
# " + carCount + " added.");
}
}
/*
* Car.java
*
* Created on April 2, 2002, 8:48 PM
*/
package singleton;
/**
*
* @author default
*/
public class Car {
/**
* Creates a new instance of Car
*
* This is nothing more than a holder class
for our example.
* We could add more detail if we really
wanted to.
*/
public Car() {
}
}
/*
* AddCarsToRoad.java
*
* Created on April 2, 2002, 8:49 PM
*/
package singleton;
/**
*
* @author default
*/
public class AddCarsToRoad {
/** Creates a new instance of AddCarsToRoad */
public AddCarsToRoad() {
}
/**
* Start from the command line. Add
as many cars as we wish.
*
*
*/
public static void main(String args[]) {
// Get the number of
cars to add from the command line.
int numberOfCars = Integer.parseInt(args[0]);
// Add the cars, one
at a time.
for (int i = 0; i <
numberOfCars; i++) {
try {
Car car = new Car();
Road road = Road.roadInstance();
road.addCar(car);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("You've added too many cars!");
}
}
}
}
Car # 1 added.
Car # 2 added.
Car # 3 added.
Car # 4 added.
Car # 5 added.
You've added too many cars!
You've added too many cars!
Created by: Brandan Jones December 17, 2001