Definition
* Cloning an object by reducing the cost of creation.
Where to use & benefits
- When there are many subclasses that differ only in the kind of objects,
- A system needs independent of how its objects are created, composed, and represented.
- Dynamic binding or loading a method.
- Use one instance to finish job just by changing its state or parameters.
- Add and remove objects at runtime.
- Specify new objects by changing its structure.
- Configure an application with classes dynamically.
- Related patterns include
- Abstract Factory, which is often used together with prototype. An abstract factory may store some prototypes for cloning and returning objects.
- Composite, which is often used with prototypes to make a part-whole relationship.
- Decorator, which is used to add additional functionality to the prototype.
The prototype means making a clone. This implies cloning of an object to avoid creation. If the cost of creating a new object is large and creation is resource intensive, we clone the object. We use the interface Cloneable and call its method clone() to clone the object.
Again let’s try and understand this with the help of a non-software example. I am stressing on general examples throughout this write-up because I find them easy to understand and easy to accept as we all read and see them in day-to-day activity. The example here we will take will be of a plant cell. This example is a bit different from the actual cloning in a way that cloning involves making a copy of the original one. Here, we break the cell in two and make two copies and the original one does not exist. But, this example will serve the purpose. Let’s say the Mitotic Cell Division in plant cells.
Let’s take a class PlantCell having a method split(). The plant cell will implement the interface Cloneable.
Following is the sample code for class PlantCell.
PlantCell.java
package creational.builder;
/**
* Shows the Mitotic cell division in the plant cell.
*/
public class PlantCell implements Cloneable {
public Object split() {
try {
return super.clone();
}catch(Exception e) {
System.out.println("Exception occured: "+e.getMessage());
return null;
}
}
}// End of class
Now let’s see, how this split method works for PlantCell class. We will make another class CellDivision and access this method.
CellDivision.java
package creational.prototype;
/**
* Shows how to use the clone.
*/
public class CellDivision {
public static void main(String[] args) {
PlantCell cell = new PlantCell();
// create a clone
PlantCell newPlantCell = (PlantCell)cell.split();
}
}// End of class
One thing is you cannot use the clone as it is. You need to instantiate the clone before using it. This can be a performance drawback. This also gives sufficient access to the data and methods of the class. This means the data access methods have to be added to the prototype once it has been cloned.
No comments:
Post a Comment