Specify the kind of objects to create using a prototypical instance, and create new objects by copying this prototype.
public interface IPerson { string FirstName { get; set; } string LastName { get; set; } int Age { get; set; } } public class Person : IPerson { public string FirstName { get; set; } public string LastName { get; set; } public int Age { get; set; } }
What we need next is an interface that defines our Clone method. One option we have is to define a custom interface which exposes our required method, such as following.
public interface ShallowClone { IPerson Clone(IPerson person); }
The alternative is to use framework interface ICloneable. For this example, we would be using the framework interface. So let’s go ahead and update the Person Class with implementation of ICloneable.
public class Person : IPerson, ICloneable { public string FirstName { get; set; } public string LastName { get; set; } public int Age { get; set; } public object Clone() => MemberwiseClone(); }
That’s all we need to do. The MemberwiseClone() method does the trick for us. We will complete the example by writing the Client code.
static void Main(string[] args) { Person personA = new Person { FirstName = "John", LastName= "Burton", Age = 35 }; Person personB = personA.Clone() as Person; Console.WriteLine($"Person A : {personA.LastName},{personA.FirstName} - Age : {personA.Age}"); Console.WriteLine($"Person B : {personB.LastName},{personB.FirstName} - Age : {personB.Age}"); }
All code samples in this example is available in my GitHub.
One thought on “Design Patterns : Prototype Pattern”