Prototype pattern

Prototype is a creational design pattern. When I first read about it, I got it a bit confused with Factory pattern. If you look at Car Factory example, where the factory helps us create a “new” car at run time, and we can choose whether we want a Sedan or Hatchback while the car creation. Prototype pattern differentiates itself from factory pattern, by providing prototypes of objects beforehand, and creating a copy at runtime.

Extending our Carfactory example further, lets say now we are not limited to 2 set of cars, but we have ready prototypes say a car called Swift, Ritz, Figo, Scorpio, all with their specifications already defined. At runtime, we will just create a copy or clone of the car which user needs. Note that we can actually build our prototype pattern on factory pattern, but for simplicity of this example we will stick to a simple implementation of car by these objects.

public class CarPrototype{

Car swift=new Car();
swift.setMaxSpeed(200);
swift.setMileage(20);
swift.setFuel(Diesel);

Car figo=new Car();
//set properties

//more cars

//we will also override clone method if required

public Car getCarFromPrototype(String str)
{
switch(str)
{
case ‘FIGO’: return figo.clone();break;
case ‘SWIFT’: retrun swift.clone();break
//so on
}
}

}

One important difference between factory and prototype is that prototype pattern creates a clone and factory pattern create a new object. When a new object is created using a new keyword, it makes sure that user get a object with fresh state. Whereas in clone (prototype), we are making sure that we are also copying a particular state of object. This also helps us understand when to use factory and when prototype should be preferred.