This Design pattern comes under creational design patterns, one of the most handy design pattern when it comes to creating the number of objects where each object's data differences is less compare to one other.
let me explain this with an example :
consider there are number of students in a batch of a course:
class Student{
String studentName;
int rollNumber;
int batch_id;
int batch_name;
String course_name;
}
if you can see in the above student class, when you go with creating multiple objects of as in each student is a object. There are no many changes between each student meaning batch_id, batch_name, course_name remains same for all students, only studentName and rollNumber going to be different for each object.
In this scenario can just go with prototype and registry design pattern.
Registry is a simple class which maintains a data structure which retrieves the object based on a key.
class StudentRegistry{
Map<String, Student> hmap=new HashMap<>();
public void register(String key,Student student){
hmap.put(key,student);
}
public Student getStudent(String key){
return hmap.get(key);
}
}
And write a copy method in student class which create the object and assign the default values beforehand for you. A ready-made object.
class Student{
String studentName;
int rollNumber;
int batch_id;
int batch_name;
String course_name;
public Student copy(){
Student student=new Student();
student.studentName = this.studentName;
student.rollNumber = this.rollNumber;
student.batch_id = this.batch_id;
student.batch_name = this.batch_name;
student.course_name = this.course_name;
return student;
}
}
Coming to Client
class client{
public static void main(String[] args){
Registry registry =new Registry();
//this method register the first object in the registry object.
registerFirstObject();
Student newStudent=registry.getStudent().copy();
newStudent.studentName="ABC";
newStudent.rollNumber=123;
}
}
isn't that easy peasy...
This method gonna make the client's life easy. So do try to implement this design pattern and make your code more efficient.
Thanks for reading... enjoy programming...