Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Designpattern The Prototype Pattern

Related Tutorials


 
 

Share on Google+Share on Google+

The Prototype Pattern

Advertisement
This pattern enables you to copy or clone of an existing object instead of creating the new one and may also customized as per the requirement.

The Prototype Pattern

     

The Prototype Pattern: 

This pattern enables you to copy or clone of an existing object instead of creating the new one and may also customized as per the requirement. It copies the existing object to avoid so much overhead. We can also use the clone method by implementing the Clonable interface to create the copy of the existing object.

Benefits: It supports for specifying the new objects with varying structure and varying values, adding and removing products at runtime, dynamically configuring the classes for an application and reducing sub-classing. 

Usage: These are used when you are not interested in constructing a class hierarchy of factories which is parallel to the class hierarchy of products. Instances of  a class can have only one combination of state, the classes are instantiated at run-time.

Example: Let's create an interface and implement it in the various classes.

Shape.java

interface Shape {
public void draw();

Square.java 

class Square implements Shape {
public void draw() {
System.out.println("square");
}
}

Circle.java 

class Circle implements Shape {
public void draw() {
System.out.println("circle");
}
}

Painting.java 

class Painting {
public static void main(String[] args) {

Shape s = new Square();
Shape c = new Circle();

paint(s);
paint(c);
}
static void paint(Shape s1) {
s1.draw();
}
}


At the runtime, the paint method takes a variable of Shape type and the draw method is called accordingly.

Overloading method is a kind of prototype pattern  too.

Painting.java 

class Painting {
public void draw(Point p, int x, int y) {
}
public void draw(Point p, int x) {
}
}


To draw the related shape the draw method is called on the bases of the parameters passed to it.

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: December 13, 2008

Related Tutorials

Discuss: The Prototype Pattern  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com