Prototype Design Pattern With Real-World Scenario

Introduction

The Prototype Pattern is among the Creational Patterns of the Gang Of Four (GOF). To understand this pattern, we first need to understand its intent.

Intent

“Specify the kind of objects to create using a prototypical instance and create a new objects by copying this prototype.” – GOF

The intent of this pattern asks us to create a new object by copying an existing one. There are two kinds of copies, a Shallow Copy and a Deep Copy. We will explain these later in this article. For now just remember we need to copy or clone the fully-initialized object. Now let us understand in detail with a real-world scenario.

Scenario

Assume there is one product-based company that provides value-added services (VAS), like Mobile Recharge, Bill Payment, DTH Recharge and so on. The entire recharge process covers the following procedure:

  1. The end user (who wants to do recharge in his own mobile) visits the Recharge Store and asks the store keeper to do a recharge, for examle Vodafone top-off of Rs. 100.
  2. The store keeper sends a request to our company.
  3. Our company sends a request to Cyberplat, the service provider.
  4. Cyberplat sends a request to the Vodafone company.
  5. Vodafone does a recharge and sends a response back to Cyberplat.
  6. Cyberplat sends the same response to our company and our company to the Recharge Store and finally sends to it to the end user.

The preceding process is called one transaction. For each transaction our company gets some discount from the service provider and shares a part of that discount with the Recharge Store. The discount received from the service provider is called an incoming discount as it is received by our company and the discount shares with the Recharge Store is called an outgoing discount since our company gives it to the Recharge Store. Until now both the discounts are fixed for all the services and operators. Now the company asks his project manager Mr. X to set various discounts for all possible combinations. Mr. X analyzed and defined four parameters to make a combination, in other words Service, Operator, Circle and Provider. Mr. X gave its name as "Product" and asked his developer Mr. Y to set an Incoming Discount and an Outgoing Discount for each product.



Approach 1

Mr. Y has started working on it. First he has created one class "Commission". In this class he has created one parameterized constructor that receives an incoming and an outgoing discount and set in the public variable.

  1. public class Commission   
  2. {  
  3.     public double IncomingCommission;  
  4.     public double OutgoingCommission;  
  5.   
  6.     public Commission(double IncomingComm, double OutgoingComm)  
  7.     {  
  8.         this.IncomingCommission = IncomingComm;  
  9.         this.OutgoingCommission = OutgoingComm;  
  10.     }  
  11. }  

In the next step he has created a class "Prototype", in which he has created properties for service, operator, circle, provider and commission. Using a parameterized constructor he receives the preceding values and set in the properties.

  1. public class Prototype   
  2. {  
  3.     private string _Service;  
  4.     private string _Operator;  
  5.     private string _Circle;  
  6.     private string _Provider;  
  7.     public Commission Comm;  
  8.     public Prototype(string Ser, string Opr, string Cir, string Pro, Commission Comm)   
  9.     {  
  10.         this._Service = Ser;  
  11.         this._Operator = Opr;  
  12.         this._Circle = Cir;  
  13.         this._Provider = Pro;  
  14.         this.Comm = Comm;  
  15.     }  
  16.   
  17.     public string Provider  
  18.     {  
  19.         get   
  20.         {  
  21.             return _Provider;  
  22.         }  
  23.         set   
  24.         {  
  25.             _Provider = value;  
  26.         }  
  27.     }  
  28.   
  29.     public string Circle   
  30.     {  
  31.         get   
  32.         {  
  33.             return _Circle;  
  34.         }  
  35.         set  
  36.         {  
  37.             _Circle = value;  
  38.         }  
  39.     }  
  40.   
  41.     public string Operator  
  42.     {  
  43.         get   
  44.         {  
  45.             return _Operator;  
  46.         }  
  47.         set   
  48.         {  
  49.             _Operator = value;  
  50.         }  
  51.     }  
  52.   
  53.     public string Service  
  54.     {  
  55.         get   
  56.         {  
  57.             return _Service;  
  58.         }  
  59.         set   
  60.         {  
  61.             _Service = value;  
  62.         }  
  63.     }  
  64. }  

Client-side Code

The client side has created an object of the class "Prototype" and set the incoming and outgoing discount for each combination of service, operator, circle and provider.

  1. class Program  
  2. {  
  3.     static void Main(string[] args)  
  4.     {  
  5.         Console.WriteLine(" Service Operator Circle Provider InComm OutComm");  
  6.         Console.WriteLine("");  
  7.   
  8.         Prototype CPT1 = new Prototype("Topup""All""Gujarat""CyberPlat"new Commission(1.0, 0.5));  
  9.         Console.WriteLine("Original Object {0} {1} {2} {3} {4} {5} ", CPT1.Service, CPT1.Operator, CPT1.Circle, CPT1.Provider, CPT1.Comm.IncomingCommission, CPT1.Comm.OutgoingCommission);  
  10.   
  11.         Console.WriteLine("");  
  12.   
  13.         Prototype CPT2 = new Prototype("Topup""All""Telengana""Euronet"new Commission(0.75, 0.25));  
  14.         Console.WriteLine("Original Object {0} {1} {2} {3} {4} {5} ", CPT2.Service, CPT2.Operator, CPT2.Circle, CPT2.Provider, CPT2.Comm.IncomingCommission, CPT2.Comm.OutgoingCommission);  
  15.   
  16.         Console.WriteLine("");  
  17.         Console.ReadKey();  
  18.     }  
  19. }  

Output

Finally he built and run the application successfully.



Mr. Y has explained his code to his project manager Mr. X. Mr. X was very happy that the code works fine. Then Mr. X explains the real-world situation. He asked Mr. Y to assume that there are 5 services, 25 operators, 29 circles and 3 providers. In this case our product count will be (5 * 25 * 29 * 3) 10875. You create an object of prototype for each product. That means you need to create an object for 10875 times to set all the discounts. This should not be done, so figure out some solution for this.


Construction is expensive

Approach 2 (Shallow Copy)

Mr. Y worked hard on this and came with the solution. In the commission class he did not change anything.

  1. public class Commission   
  2. {  
  3.     public double IncomingCommission;  
  4.     public double OutgoingCommission;  
  5.   
  6.     public Commission(double IncomingComm, double OutgoingComm)  
  7.     {  
  8.         this.IncomingCommission = IncomingComm;  
  9.         this.OutgoingCommission = OutgoingComm;  
  10.     }  
  11. }  

In the next step he has converted a prototype class into an abstract class. He has also added one abstract method "Clone" in the prototype class.

  1. abstract class Prototype   
  2. {  
  3.     private string _Service;  
  4.     private string _Operator;  
  5.     private string _Circle;  
  6.     private string _Provider;  
  7.     public Commission Comm;  
  8.     public Prototype(string Ser, string Opr, string Cir, string Pro, Commission Comm)   
  9.     {  
  10.         this._Service = Ser;  
  11.         this._Operator = Opr;  
  12.         this._Circle = Cir;  
  13.         this._Provider = Pro;  
  14.         this.Comm = Comm;  
  15.     }  
  16.   
  17.     public string Provider   
  18.     {  
  19.         get   
  20.         {  
  21.             return _Provider;  
  22.         }  
  23.         set   
  24.         {  
  25.             _Provider = value;  
  26.         }  
  27.     }  
  28.   
  29.     public string Circle   
  30.     {  
  31.         get  
  32.         {  
  33.             return _Circle;  
  34.         }  
  35.         set   
  36.         {  
  37.             _Circle = value;  
  38.         }  
  39.     }  
  40.   
  41.     public string Operator   
  42.     {  
  43.         get   
  44.         {  
  45.             return _Operator;  
  46.         }  
  47.         set   
  48.         {  
  49.             _Operator = value;  
  50.         }  
  51.     }  
  52.   
  53.     public string Service   
  54.     {  
  55.         get   
  56.         {  
  57.             return _Service;  
  58.         }  
  59.         set   
  60.         {  
  61.             _Service = value;  
  62.         }  
  63.     }  
  64.     public abstract Prototype Clone();  
  65. }  

Then he has created one more class "ConcretePrototypeTopup" and inherited the "Prototype" class. In this concrete prototype class he has implemented an abstract method "Clone". In this method he returned the copy of the existing object using the MemberwiseClone method.

  1. class ConcretePrototypeTopup: Prototype  
  2. {  
  3.     public ConcretePrototypeTopup(string Ser, string Opr, string Cir, string Pro, Commission Comm): base(Ser, Opr, Cir, Pro, Comm)   
  4.     {  
  5.   
  6.     }  
  7.   
  8.     public override Prototype Clone()  
  9.     {  
  10.         return (Prototype) this.MemberwiseClone();  
  11.     }  
  12. }  

Now let's check what Mr. Y has created so far using a class diagram. Mr. Y has created an abstract class called "Prototype" and one concrete prototype class that implements an abstract method.



Participants

Prototype: An abstract class that defined the method to clone itself.

ConcretePrototype: Concrete class that implements an abstract method to clone itself.

Client: Requires the cloned copy of the object.

Client-side Code

In the client-side:

  1. He has created an object of a concrete prototype and set the values, consider it as the original object.
  2. He has create another object by copying the preceding one using MemberwiseClone, consider it as a shallow copy.
  3. He changed the values of the shallow copy object.
  4. He checked the values for the original object.
  1. class Program   
  2. {  
  3.     static void Main(string[] args)   
  4.     {  
  5.         Console.WriteLine("                  Service    Operator    Circle    Provider     InComm  OutComm");  
  6.         Console.WriteLine("");  
  7.   
  8.         ConcretePrototypeTopup CPT1 = new ConcretePrototypeTopup("Topup""All""Gujarat""CyberPlat"new Commission(1.0, 0.5));  
  9.   
  10.         Console.WriteLine("Original Object   {0}      {1}         {2}   {3}    {4}       {5} ", CPT1.Service, CPT1.Operator, CPT1.Circle, CPT1.Provider, CPT1.Comm.IncomingCommission, CPT1.Comm.OutgoingCommission);  
  11.         Console.WriteLine("");  
  12.   
  13.         ConcretePrototypeTopup CPT2 = (ConcretePrototypeTopup) CPT1.Clone();  
  14.   
  15.         Console.WriteLine("Shallow Copy      {0}      {1}         {2}   {3}    {4}       {5}", CPT2.Service, CPT2.Operator, CPT2.Circle, CPT2.Provider, CPT2.Comm.IncomingCommission, CPT2.Comm.OutgoingCommission);  
  16.         Console.WriteLine("");  
  17.   
  18.         CPT2.Circle = "Telengana";  
  19.         CPT2.Provider = "Euronet";  
  20.         CPT2.Comm.IncomingCommission = 0.75;  
  21.         CPT2.Comm.OutgoingCommission = 0.25;  
  22.   
  23.         Console.WriteLine("Change Shallow    {0}      {1}         {2}   {3}    {4}       {5}", CPT2.Service, CPT2.Operator, CPT2.Circle, CPT2.Provider, CPT2.Comm.IncomingCommission, CPT2.Comm.OutgoingCommission);  
  24.         Console.WriteLine("");  
  25.   
  26.         Console.WriteLine("Original Object   {0}      {1}         {2}   {3}    {4}       {5}", CPT1.Service, CPT1.Operator, CPT1.Circle, CPT1.Provider, CPT1.Comm.IncomingCommission, CPT1.Comm.OutgoingCommission);  
  27.         Console.WriteLine("");  
  28.   
  29.         Console.ReadKey();  
  30.     }  
  31. }  
Output

Mr. Y built and run the application successfully. Now please check the 3rd and 4th row in the output very closely. In the 3rd row Mr. Y has changed the values for circle, provider, incoming commission and outgoing commission for the shallow copied object. Then in the 4th row Mr. Y checked the values for the original object. You can see that the values for circle and provider did not change, in other words it matched the original object but the values for the incoming commission and outgoing commission are changed with the shallow copy object. The reason is the MemberwiseClone method creates a shallow copy by creating a new object and then copying the nonstatic fields of the current object to the new object. If a field is a value type then a bit-by-bit copy of the field is done. If a field is a reference type, the reference is copied but the referred object is not; therefore, the original object and its clone refer to the same object.



Before demonstrating the preceding code to his project manager Mr. X, Mr. Y thought that Mr. X might ask "What if I don't want to affect or change the original object?", hence Mr. Y has created one more sample.

Approach 3 (Deep Copy)

In this approach Mr. Y has implemented an ICloneable interface in the Commission class. In the Clone method he used the MemberwiseClone method for this class object.

  1. public class Commission : ICloneable  
  2. {  
  3.     public double IncomingCommission;  
  4.     public double OutgoingCommission;  
  5.   
  6.     public Commission(double IncomingComm,double OutgoingComm)  
  7.     {  
  8.         this.IncomingCommission = IncomingComm;  
  9.         this.OutgoingCommission = OutgoingComm;  
  10.     }  
  11.   
  12.     public object Clone()  
  13.     {  
  14.         return this.MemberwiseClone();  
  15.     }  
  16. }  
In the Prototype class, he has converted the commission variable into a property to be defined by its class constructor.
  1. abstract class Prototype   
  2. {  
  3.     private string _Service;  
  4.     private string _Operator;  
  5.     private string _Circle;  
  6.     private string _Provider;  
  7.     private Commission _Commission;  
  8.     public Prototype(string Ser, string Opr, string Cir, string Pro, Commission Comm)   
  9.     {  
  10.         this._Service = Ser;  
  11.         this._Operator = Opr;  
  12.         this._Circle = Cir;  
  13.         this._Provider = Pro;  
  14.         this.Comm = Comm;  
  15.     }  
  16.   
  17.     public Commission Comm   
  18.     {  
  19.         get  
  20.         {  
  21.             return _Commission;  
  22.         }  
  23.         set  
  24.         {  
  25.             _Commission = value;  
  26.         }  
  27.     }  
  28.     public string Provider   
  29.     {  
  30.         get   
  31.         {  
  32.             return _Provider;  
  33.         }  
  34.         set   
  35.         {  
  36.             _Provider = value;  
  37.         }  
  38.     }  
  39.   
  40.     public string Circle   
  41.     {  
  42.         get  
  43.         {  
  44.             return _Circle;  
  45.         }  
  46.         set   
  47.         {  
  48.             _Circle = value;  
  49.         }  
  50.     }  
  51.   
  52.     public string Operator   
  53.     {  
  54.         get   
  55.         {  
  56.             return _Operator;  
  57.         }  
  58.         set   
  59.         {  
  60.             _Operator = value;  
  61.         }  
  62.     }  
  63.   
  64.     public string Service   
  65.     {  
  66.         get   
  67.         {  
  68.             return _Service;  
  69.         }  
  70.         set   
  71.         {  
  72.             _Service = value;  
  73.         }  
  74.     }  
  75.     public abstract Prototype Clone();  
  76. }  

In the concrete prototype class, he has implemented an abstract method "Clone". In this method he has created a copy of members that are value types and then created a new instance of commission by calling its Clone method.

  1. class ConcretePrototypeTopup: Prototype  
  2. {  
  3.     public ConcretePrototypeTopup(string Ser, string Opr, string Cir, string Pro, Commission Comm): base(Ser, Opr, Cir, Pro, Comm)  
  4.     {  
  5.   
  6.     }  
  7.     public override Prototype Clone()   
  8.     {  
  9.         ConcretePrototypeTopup objCPT = (ConcretePrototypeTopup) this.MemberwiseClone();  
  10.         objCPT.Comm = (Commission) this.Comm.Clone();  
  11.         return objCPT;  
  12.     }  
  13. }  

Now let's check what Mr. Y has created so far, using a class diagram. Mr. Y has implemented the ICloneable interface in the Commission class. Mr. Y has also created and an abstract class called "Prototype" and one concrete prototype class that implements an abstract method.



Client-side Code

In the client side:

  1. He has created an object of concrete prototype and set the values, consider it as the original object.
  2. He has create another object by copying the preceding one using the Clone abstract method, consider it as a deep copy.
  3. He changed the values of the deep copy object.
  4. He checked the values for the original object.
  1. class Program  
  2. {  
  3.     static void Main(string[] args)  
  4.     {  
  5.         Console.WriteLine("                  Service    Operator    Circle    Provider     InComm  OutComm");  
  6.         Console.WriteLine("");  
  7.         ConcretePrototypeTopup CPT1 = new ConcretePrototypeTopup("Topup""All""Gujarat""CyberPlat"new Commission(1.0, 0.5));  
  8.   
  9.         Console.WriteLine("Original Object   {0}      {1}         {2}   {3}    {4}       {5} ", CPT1.Service, CPT1.Operator, CPT1.Circle, CPT1.Provider, CPT1.Comm.IncomingCommission, CPT1.Comm.OutgoingCommission);  
  10.         Console.WriteLine("");  
  11.   
  12.         ConcretePrototypeTopup CPT2 = (ConcretePrototypeTopup) CPT1.Clone();  
  13.   
  14.         Console.WriteLine("Deep Copy         {0}      {1}         {2}   {3}    {4}       {5}", CPT2.Service, CPT2.Operator, CPT2.Circle, CPT2.Provider, CPT2.Comm.IncomingCommission, CPT2.Comm.OutgoingCommission);  
  15.         Console.WriteLine("");  
  16.   
  17.         CPT2.Circle = "Telengana";  
  18.         CPT2.Provider = "Euronet";  
  19.         CPT2.Comm.IncomingCommission = 0.75;  
  20.         CPT2.Comm.OutgoingCommission = 0.25;  
  21.   
  22.         Console.WriteLine("Change Deep       {0}      {1}         {2}   {3}    {4}       {5}", CPT2.Service, CPT2.Operator, CPT2.Circle, CPT2.Provider, CPT2.Comm.IncomingCommission, CPT2.Comm.OutgoingCommission);  
  23.         Console.WriteLine("");  
  24.         Console.WriteLine("Original Object   {0}      {1}         {2}   {3}    {4}       {5}", CPT1.Service, CPT1.Operator, CPT1.Circle, CPT1.Provider, CPT1.Comm.IncomingCommission, CPT1.Comm.OutgoingCommission);  
  25.         Console.WriteLine("");  
  26.         Console.ReadKey();  
  27.     }  
  28. }  

Output

Mr. Y has built and run the application successfully. Here we can see in the 4th row that the value of the original object is not changed with the deep copy object.



Comparison

Mr. Y has explained both the application code to his project manager Mr. X and has shown the demo by comparing the output of the shallow copy and deep copy. Mr. X was very happy since now there is no need to create an object 10875 times.

Shallow Copy



Deep Copy



Summary

When construction of an object is expensive or we want to hide the constructor, we can use "The Prototype Pattern".


Similar Articles