Monday, June 25, 2012

Prototype Design Pattern

Introduction

Prototype design pattern is one of a creational design pattern. This pattern can be used when user wants to have an object but without instanciating it. That means using java clone feature. The advantage of this pattern is as you might know creating an object using new operator is very costly. But here we use clone method to create new objects. But you know if we want to create an object using clone method there should be existing object to make clone objects. So first object creation should be done by using the java new operator.

Example 

Suppose you want to draw some shapes. For example you want to draw shapes like Square, Triangle. But these drawing not only once. many times you want to draw Square and Triangle. In other words, you have to make instances of Square and Triangle classes. But you want to avoid that instance creation but make instances by cloning. So it is the prototype design pattern.

Following example code has Shape abstract class and Square and Triangle concrete classes. As you can see Shape class implement with Cloneable interface so that it can implement of cloning logic.

Shape.java

package com.blog.patterns.prototype;

/**
 * @author uditha
 */
public abstract class Shape implements Cloneable {

 public abstract void draw();
 
 @Override
 public Object clone() {
  Object clone = null;
  try {
   clone = super.clone();
  } catch (CloneNotSupportedException e) {
   e.printStackTrace();
  }
  return clone;
 }
 
}

Square.java

package com.blog.patterns.prototype;

/**
 * @author uditha
 */
public class Square extends Shape {

 @Override
 public void draw() {
  System.out.println("Square");
 }
 
}

Triangle.java

package com.blog.patterns.prototype;

/**
 * @author uditha
 */
public class Triangle extends Shape {

 @Override
 public void draw() {
  System.out.println("Triangle");
 }
 
}

Main.java

package com.blog.patterns.prototype;

/**
 * @author uditha
 */
public class Main {
 
 public static void main(String[] args) {
  Shape squareA = new Square();
  squareA.draw();
  Shape squareB = (Square) squareA.clone();
  squareB.draw();
  
  Shape triangleA = new Triangle();
  triangleA.draw();
  Shape triangleB = (Triangle) triangleA.clone();
  triangleB.draw();
 }

}

4 comments:

  1. Your observations are right on, I totally agree with most of what you say. You are a good writer. You should share more for people to read. Thank you so much! I will wait for you.
    Design Prototype

    ReplyDelete
  2. Thank you albertsina for your comment :-)

    ReplyDelete
  3. This is good explanation. Thanks

    ReplyDelete
  4. It is really a great work and the way in which u r sharing the knowledge is excellent.
    Thanks for helping me to understand design concepts. As a beginner in java programming your post help me a lot.Thanks for your informative article.java training in chennai

    ReplyDelete