Thursday, January 13, 2011

Java design pattern

Summary: Allow user to know 23 methods of design pattern


TABLE 1
Prototype(1,1)Template(1,2)Bridges(1,3)
(2,1)(2,2)(2,3)
(3,1)(3,2)(3,3)
JAVA DESIGN PATTERNS
Creational Patterns - Prototype Pattern
Example : Cloning a sheep
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
TABLE 2
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
TABLE 3
package creational.prototype;/*** Shows how to use the clone.*/public class CellDivision {
 public static void main(String[] args) {PlantCell cell = new PlantCell(); // create a clonePlantCell 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

Related Posts Plugin for WordPress, Blogger...

java

Popular java Topics