When to use?
This design pattern is used when:
--> Creation of new objects is costly/time intensive.
How to use?
In .Net world we have something called as "MemberwiseClone()". MemberwiseClone method when invoked on some class, will return a shallow copy of the class's object.
Example:
We have a class named Employee:
class Employee
{
int EmpID;
string EmployeeName;
}In the client or the Main method we will create the object like this:
Employee objEmployee1 = new Employee();
If we need to create another object of Employee class we can create it like this:
Employee objEmployee2 = new Employee();
Now, instead of creating the object objEmployee2, we can also create it without the new operator with Employee i.e by implementing the Prototype Pattern.
Implementing Prototype Pattern:
The modifications required for implementing the Prototype pattern are:
--> Addition of Clone method in the Employee Class
--> Calling the Clone method in the client to copy the object instead of creating a new one from the scratch.
Now inorder to add the Clone method, we would implement the IClonable interface in Employee class:
Here is the new code:
class Employee : IClonable
{
int EmpID;
string EmployeeName;
public Employee Clone()
{
return (Employee)this.MemberwiseClone();
}
}In the client or the Main method we will create the objects like this:
Employee objEmployee1 = new Employee();
Creation of second object with Cloning:
Employee objEmployee2 = objEmployee1.Clone();
Now in objEmployee2, all the values that would be set in the objEmployee1 object would still be there, but both of these objects would be referring to different addresses as we have cloned them.