Prototype design pattern is used when the creation of objects take too much of system ressources and performances, and we use this design pattern exactly when we want to have many instances of a class, and those instances are similar, so we don’t really want to use for example the operator “new” because it will be so costly, all that we need is to instantiate those objects basing on the first one already created.
the advantage is that the new object will be independent and it will not take too much of ressources to be created as the first one.
here an example of using this concept in java:
import java.util.Vector;
public class Samsung implements Cloneable{
private Vector<String> models;
public Samsung(){
models=new Vector<>();
//we suppose in this comments we access to a data Base to get models
//and then we get a full list of Samsung models
//... and finish
//Sadly we took to much of time to fetch the database
//we don't want to waste our time again because Samsung rarely update its database
models.add("Samsung S1");
models.add("Samsung S2");
models.add("galaxy note");
models.add("galaxy star");
}
public Samsung(Vector<String> models){
this.models=models;
}
public Samsung clone() {
Vector<String> modelsCopy=new Vector<>();
Samsung samsungCopy=null;
//here we don't need to access the database again, we will just copy the previous list
try{
for(String model:this.models){
modelsCopy.add(model);
}
samsungCopy=new Samsung(modelsCopy);
return samsungCopy;
}
catch(Exception e){
return null;
}
}
}
the main program :
public static void main(String[] args) {
Samsung usa_Samsung=new Samsung();
Samsung morocco_Samsung=usa_Samsung.clone();
System.out.println("original = " + usa_Samsung);
System.out.println("copy = " + morocco_Samsung);
}
output :
original = Samsung@6d06d69c
copy = Samsung@7852e922
like you see these objects have not the same address because they are different .
Note !
i used the name “Samsung” only as an example.