Prototype



The prototype pattern works by providing prototype
objects that can be cloned to produce more.


This is the abstract class all 'cloneable' classes
will extend.
Notice it implements the Cloneable interface.
The class Object (which all java classes extend)
implements the clone function but it is private 
so this class must make this function
public.
-----------------------------------------------------
public abstract class Vehicle implements Cloneable{

    private int maxSpeed;
    
    public Object clone(){
        try{
            return super.clone();
        }catch(Throwable t){throw new InternalError();}
    }
    
    public int getMaxSpeed(){return maxSpeed;}
    public void setMaxSpeed(int maxSpeed){this.maxSpeed=maxSpeed;}
}
-----------------------------------------------------


This class provides the cloned objects to the client.
-----------------------------------------------------
class VehicleManager{
    private Vector vehicles = new Vector();

    public void addVehicle(Object temp){
        vehicles.add(temp);
    }

    public Vehicle getRandomVehicle(){
        Random ran = new Random();
        
        return  (Vehicle)((Vehicle)vehicles.elementAt
            (ran.nextInt(vehicles.size()))).clone();
    }
}
-----------------------------------------------------



This class provides the manager class with the initial
objects.
-----------------------------------------------------
class VehicleBuilder{
    
    private VehicleManager vehicleManager;
    
    public VehicleBuilder(VehicleManager vm){
        this.vehicleManager = vm;
    }

    public void loadVehicles(){
        /*
          this is hard coded
          objects could have been read 
          from a file or dynamiclly
          aquired.
        */ 
        vehicleManager.addVehicle(new Motercycle());
        vehicleManager.addVehicle(new Car());
    }

}
-----------------------------------------------------

A concrete 'clonable' class.
-----------------------------------------------------
class Motercycle extends Vehicle{}
-----------------------------------------------------


A concrete 'clonable' class.
-----------------------------------------------------
class Car extends Vehicle{}
-----------------------------------------------------


A test stub to run it all.
-----------------------------------------------------
class Test{

    public static void main(String[] args){
        System.out.println("class: Test, method: main");

        VehicleManager vehicleManager = new VehicleManager();
        VehicleBuilder vehicleBuilder = new VehicleBuilder(vehicleManager);
        vehicleBuilder.loadVehicles();

        Vehicle aVehicle = vehicleManager.getRandomVehicle();
        System.out.println(aVehicle.getClass().getName());
    }
}
-----------------------------------------------------



Here is a tar with the above java classes in it. 
prototype.tar


Related subjects: 
Deep vrs Shallow copy
Dynamic linkage