Prototype comes under creational design pattern.
It simplifies the object creation by cloning from existing instance.
Making an object copy from existing instance saves both time and memory.
In Java we know Strings are immutable and as cloned objects share the
same string references, it provides a sort of memory optimization.
Behaviour & Advantages
It avoids the cost of creating new instance.
Creates a new object by copying its properties.
This example shows cloning an Employee object.
For that we need to implement java.lang.Cloneable interface.
Class java.lang.Object has a native implementation of clone() method which returns a
Shallow copy of the current object. Invoking clone() method on object without implementing java.lang.Cloneable
interface results in java.lang.CloneNotSupportedException exception.
public void setName(String name) { this.name = name;
}
public String getDesignation() { return designation;
}
public void setDesignation(String designation) { this.designation = designation;
}
public int getSalary() { return salary;
}
public void setSalary(int salary) { this.salary = salary;
}
public int[] getLuckyNums() { return luckyNums;
}
public void setLuckyNums(int[] luckyNums) { this.luckyNums = luckyNums;
}
}
In Shallow copy primitive values are copied by value and objects by reference.
In Java Arrays (both primitive & object) are considered as objects and hence copied by reference.
So changes to the array in original object reflects in the cloned object or vice versa.
We can observe that primitive value (salary) change in cloned object didn't effect the same in original
object. However the changes we have made for object (luckyNums) effect the original object.
if (other.luckyNums != null) { this.luckyNums = new int[other.luckyNums.length]; for (int i = 0 ; i < other.luckyNums.length ; i ++) { this.luckyNums[i] = other.luckyNums[i];
}
}
}
public Employee2 clone() { return new Employee2(this);
}