Thursday, May 26, 2016

Tutorial on Prototype Design Pattern tutorial example java

As the name suggests, Prototype means making a clone. and Cloning is the operation of replicating an object.The cloned object the copy is initialized with the current state of the object on which clone was invoked.
So when we talk about Object creation,we can find a better way to have new objects.

Let say construction of a home ,Home is the final end product(Object) that is to be returned as the output of the construction process. So to create home we have go to through many steps such as Wall Creation,Roof Creation and Basement Creation and So on.Finally the whole home object is returned.

Cloning an object is based on the concepts of Shallow and Deep Cloning.

Shallow Cloning : When the original object changed ,the new object is changed as well.
 Question is Why?
Because the shallow copy  makes copies of only the references and not the object to which they refer.

Deep Cloning:  When the original object is modified the new object remains unaffected ,since the entire set of objects to which the original object refers to were copied as well.

Keep it in mind that copying involves primitive types ie. byte .

Basically the Prototype Pattern involves three things-
1) Client : creates a new object by asking a prototype to clone itself.
2) Prototype: declares an interface for cloning itself.
3)Concrete-Prototype: implements the operation for cloning itself.

Java has built in clone method.

Implementation should be something like this:

public class Animal clone()
{
  Animal clonnedAnimal=null;
  try
  {
    clonnedAnimal =(Animal)super.colne();
clonnedAnimal.setDescription(description);
clonnedAnimal.setNumberofLegs(numberOFLegs);
clonnedAnimal.setName(name);
  }
  catch(CloneNotSupportedExeception e)
  {
    e.prntStackTrace();
  }

  return clonnedAnimal;
}




public class Sheep extends Animal{

}

public class Chicken extends Animal{

}



public Animal retrieveAnimal(String kindOfAnimal)
{
  if("chicken").equals(kindOfAnimal)
  {
    return (Animal)chicken.clone();
  }
  else if("Sheep").equals(kindOfAnimal)
  {
    return (Animal)Sheep.clone();
  }
  return null;
}

AnimalCreator animalCreator= new AnimalCreator();
Animal[] animalFarm= new Animal[2];

animalFarm[0]=animalCreator.retrieveAnimal("Chicken");
animalFarm[1]=animalCreator.retrieveAnimal("Sheep");

for(int i=0;i<=3;i++)
{
  System.out.println(animalFarm[i].helloAnimal());
}


When to use Prototype Design Pattern:

- when a system should be independent of how its products are created,composed and represented.

-Implementing Clone can be difficult when their internals include objects that do not support copying or have circular references.




No comments: