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.

The Prototype Pattern

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.