Prototype pattern gives us a way to create new objects from the existing instance of the object.
That is, we clone the existing object with its data. By cloning any changes to the cloned object does not affect the original object value.
In below example i have used ProtoTypePattern which need to be clonned. This can be achieved by using MemberWiseClone method.
Create ProtoTypePattern.cs class file and add below code.
using System;
namespace dotnetfundamentals.DesignPatterns
{
//This is the class to be Cloned
public class ProtoTypePattern
{
public string sName { get; set; }
public ProtoTypePattern getClone()
{
//MemberWiseClone function will cereate complete new cpoy of object
return (ProtoTypePattern)this.MemberwiseClone();
}
}
}
Add below code in Program.cs file.
using System;
namespace dotnetfundamentals.DesignPatterns
{
class Program
{
static void Main(string[] args)
{
//This is the first copy of the the object
ProtoTypePattern protoType1 = new ProtoTypePattern();
//This will set the value for the first object.
protoType1.sName = "Patel Himen";
//This is the second copy of object
ProtoTypePattern protoType2 = new ProtoTypePattern();
//This will create copy of the object
protoType2.getClone();
}
}
}