Design Patterns : Prototype Pattern

Falling under Creational Patterns, Prototype Pattern aims in creating a clone of your object and is used in scenarios when creating a object is considered costly (may be the creation involves a long Database or Web Service Operation). The formal definition of the pattern is as follows.

 

Specify the kind of objects to create using a prototypical instance, and create new objects by copying this prototype.
It is one of the most easiest patterns to implement using .Net Framework.  Let’s define our target class first.
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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s