Prototype Pattern In C#

Prototype Pattern

Prototype Pattern comes under the creation type design pattern. It is used for creating duplicate objects or for cloning an object. You can create prototype instance.

You can use this pattern when creation of object is very complex or costly.

Below is a sample for the same 
  1. abstract class Prototype {  
  2.     private string _id;  
  3.     // Constructor  
  4.     public Prototype(string id) {  
  5.         this._id = id;  
  6.     }  
  7.     // Gets id  
  8.     public string Id {  
  9.         get {  
  10.             return _id;  
  11.         }  
  12.     }  
  13.     public abstract Prototype Clone();  
  14. }   

The above class is a Prototype class (You can create Interface also)

Now, 

  1. class ConcretePrototype1: Prototype {  
  2.     // Constructor  
  3.     public ConcretePrototype1(string id): base(id) {}  
  4.     // Returns a shallow copy  
  5.     public override Prototype Clone() {  
  6.         return (Prototype) this.MemberwiseClone();  
  7.     }  
  8. }   

Above is Concrete Prototype class which is implementing Prototype

  1. class ConcretePrototype2: Prototype {  
  2.     // Constructor  
  3.     public ConcretePrototype2(string id): base(id) {}  
  4.     // Returns a shallow copy  
  5.     public override Prototype Clone() {  
  6.         return (Prototype) this.MemberwiseClone();  
  7.     }  
  8. }  
  9. }   

Above is Concrete Prototype class too which is implementing Prototype 

  1. class MainApp {  
  2.     static void Main() {  
  3.         // Create two instances and clone each  
  4.         ConcretePrototype1 p1 = new ConcretePrototype1("This is Concrete 1");  
  5.         ConcretePrototype1 c1 = (ConcretePrototype1) p1.Clone();  
  6.         Console.WriteLine("Cloned: {0}", c1.Id);  
  7.         ConcretePrototype2 p2 = new ConcretePrototype2("This is Concrete 2");  
  8.         ConcretePrototype2 c2 = (ConcretePrototype2) p2.Clone();  
  9.         Console.WriteLine("Cloned: {0}", c2.Id);  
  10.         Console.ReadLine();  
  11.     }  
Next Recommended Reading Design Patterns in C#