prototype design pattern real time example

In this section, we will elaborate on the importance of prototype design pattern with real time example. Let’s discuss first, what is a prototype? prototype means a prototype-design-pattern-real-time-examplemodel or template of the first design, from which many other duplicates are created based on the first template.what is a prototype design pattern in java? it is one of the creational design patterns which is used to create the objects without using the new operator. we create an object of the same kind by cloning by implementing the cloneable interface. there are easy steps to implement this approach. In the first step, we need to implement the cloneable interface. the second step will be, implement the override clone method. third will be, we have to write the cloning logic in the overridden clone method.

Real time example to understand the prototype design pattern:

public class PrototypedesignDemo {
public static void main(String[] args) {
Student s1 = new Student();
s1.setName("maxwell");
s1.setStudentId("1001");
try {
Student s2 = (Student) s1.clone(); //S2 will be duplicate object of S1
s1.showInfo(); 
s1.setName("joel"); 
s2.showInfo();
} catch (CloneNotSupportedException e) {

e.printStackTrace();
}
Student s3 = s1; // it is not same as clone operation , s3 will be referencing to the s1 object
s3.showInfo(); 
}
}

class Student implements Cloneable {
private String name;
private String studentId;

@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getStudentId() {
return studentId;
}

public void setStudentId(String studentId) {
this.studentId = studentId;
}

public void showInfo() {
System.out.println("student name::" + name + " with Id::" + studentId);
}
}

Expected output:

student name::maxwell with Id::1001
student name::maxwell with Id::1001
student name::joel with Id::1001

why we use prototype design pattern?

1. when we want to have a copy of an existing object, we no need complex logic for getting a copy. the complete setup is already free.

2. we don’t need to know the concrete class of the object we are creating. we are programming to interfaces, not Implementations.

3. network or database calls, instead of multiple calls, we can perform necessary changes on the copy object.

application performance will be improved and saves object creation cost, lots of time by implementing this approach. Thank you for reading the post. please post your comments in the comment box.

 

 


Posted

in

by

Tags:

Comments

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Design a site like this with WordPress.com
Get started