Skip to main content

Prototype Design Pattern - C#

Prototype pattern falls under Creational Pattern of Gang of Four (GOF) Design Patterns in .Net. It is used to create a duplicate object or clone of the current object. It provides an interface for creating parts of a product. In this article, we will see what is Prototype pattern and how is it work?

What is Prototype Pattern?

Prototype pattern is used to create a duplicate object or clone of the current object to enhance performance. This pattern is used when creation of object is costly or complex.
For Example: An object is to be created after a costly database operation. We can cache the object, returns its clone on next request and update the database as and when needed thus reducing database calls.

Prototype Pattern - UML Diagram & Implementation

The UML class diagram for the implementation of the Prototype design pattern is given below:
The classes, interfaces and objects in the above UML class diagram are as follows:
  1. Prototype

    This is an interface which is used for the types of object that can be cloned itself.
  2. ConcretePrototype

    This is a class which implements the Prototype interface for cloning itself.

C# - Implementation Code

  1. public interface IPrototype
  2. {
  3. IPrototype Clone();
  4. }
  5. public class ConcretePrototypeA : IPrototype
  6. {
  7. public IPrototype Clone()
  8. {
  9. // Shallow Copy: only top-level objects are duplicated
  10. return (IPrototype)MemberwiseClone();
  11. // Deep Copy: all objects are duplicated
  12. //return (Prototype)this.Clone();
  13. }
  14. }
  15.  
  16. public class ConcretePrototypeB : IPrototype
  17. {
  18. public IPrototype Clone()
  19. {
  20. // Shallow Copy: only top-level objects are duplicated
  21. return (IPrototype)MemberwiseClone();
  22. // Deep Copy: all objects are duplicated
  23. //return (Prototype)this.Clone();
  24. }
  25. }

Prototype Pattern - Example

Who is what?

The classes, interfaces and objects in the above class diagram can be identified as follows:
  1. IEmployee - Prototype interface
  2. Developer & Typist- Concrete Prototype

C# - Sample Code

  1. /// <summary>
  2. /// The 'Prototype' interface
  3. /// </summary>
  4. public interface IEmployee
  5. {
  6. IEmployee Clone();
  7. string GetDetails();
  8. }
  9.  
  10. /// <summary>
  11. /// A 'ConcretePrototype' class
  12. /// </summary>
  13. public class Developer : IEmployee
  14. {
  15. public int WordsPerMinute { get; set; }
  16. public string Name { get; set; }
  17. public string Role { get; set; }
  18. public string PreferredLanguage { get; set; }
  19.  
  20. public IEmployee Clone()
  21. {
  22. // Shallow Copy: only top-level objects are duplicated
  23. return (IEmployee)MemberwiseClone();
  24.  
  25. // Deep Copy: all objects are duplicated
  26. //return (IEmployee)this.Clone();
  27. }
  28.  
  29. public string GetDetails()
  30. {
  31. return string.Format("{0} - {1} - {2}", Name, Role, PreferredLanguage);
  32. }
  33. }
  34.  
  35. /// <summary>
  36. /// A 'ConcretePrototype' class
  37. /// </summary>
  38. public class Typist : IEmployee
  39. {
  40. public int WordsPerMinute { get; set; }
  41. public string Name { get; set; }
  42. public string Role { get; set; }
  43.  
  44. public IEmployee Clone()
  45. {
  46. // Shallow Copy: only top-level objects are duplicated
  47. return (IEmployee)MemberwiseClone();
  48.  
  49. // Deep Copy: all objects are duplicated
  50. //return (IEmployee)this.Clone();
  51. }
  52.  
  53. public string GetDetails()
  54. {
  55. return string.Format("{0} - {1} - {2}wpm", Name, Role, WordsPerMinute);
  56. }
  57. }
  58.  
  59. /// <summary>
  60. /// Prototype Pattern Demo
  61. /// </summary>
  62.  
  63. class Program
  64. {
  65. static void Main(string[] args)
  66. {
  67. Developer dev = new Developer();
  68. dev.Name = "Rahul";
  69. dev.Role = "Team Leader";
  70. dev.PreferredLanguage = "C#";
  71.  
  72. Developer devCopy = (Developer)dev.Clone();
  73. devCopy.Name = "Arif"; //Not mention Role and PreferredLanguage, it will copy above
  74.  
  75. Console.WriteLine(dev.GetDetails());
  76. Console.WriteLine(devCopy.GetDetails());
  77.  
  78. Typist typist = new Typist();
  79. typist.Name = "Monu";
  80. typist.Role = "Typist";
  81. typist.WordsPerMinute = 120;
  82.  
  83. Typist typistCopy = (Typist)typist.Clone();
  84. typistCopy.Name = "Sahil";
  85. typistCopy.WordsPerMinute = 115;//Not mention Role, it will copy above
  86.  
  87. Console.WriteLine(typist.GetDetails());
  88. Console.WriteLine(typistCopy.GetDetails());
  89.  
  90. Console.ReadKey();
  91.  
  92. }
  93. }

Prototype Pattern Demo - Output

When to use it?

  1. The creation of each object is costly or complex.
  2. A limited number of state combinations exist in an object.

Comments

Popular posts from this blog

Accessing File Stored in Windows Azure Blob Storage Using jQuery

Did you know it was possible to access the Windows Azure Blob Storage directly from JavaScript, for example using jQuery? At first, it sounds obvious, since Blobs are after all accessible from a public UR. But in practice, there is a very big hurdle: the Web browser’s Same Origine Policy or SOP, that restricts JavaScript code to accessing resources originating from the same site the script was loaded from. This means that you will never be able to load a Windows Azure Blob using XMLHttpRequest for example! Fortunately, there is a popular workaround called JSONP (“JSON with Padding”). The idea behind this technique is that the script tag is not submitted to the SOP: an HTML page can thus load a JavaScript file from any site. So, if you expose your data in an “executable” form in JavaScript, a page will be able to load this data using a script tag. For example: <script type=”text/javascript” src=”http://www.sandeepknarware.in/exemple.jsonp”> </script> But how can ...

Support for debugging lambda expressions with Visual Studio 2015

Anyone who uses LINQ (or lambdas in general) and the debugger will quickly discover the dreaded message “Expression cannot contain lambda expressions”. Lack of lambda support has been a limitation of the Visual Studio Debugger ever since Lambdas were added to C# and Visual Basic.  With visual studio 2015 Microsoft has added support for debugging lambda expressions. Let’s first look at an example, and then I’ll walk you through current limitations. Example To try this yourself, create a new C# Console app with this code: using System.Diagnostics; using System.Linq; class Program { static void Main() { float[] values = Enumerable.Range(0, 100).Select(i => (float)i / 10).ToArray(); Debugger.Break(); } } Then compile, start debugging, and add “values.Where(v => (int)v == 3).ToArray()” in the Watch window. You’ll be happy to see the same as what the screenshot above shows you. I am using Visual Studio 2015 Preview and it has some limitati...

gcAllowVeryLargeObjects Element

There are numerous new features coming with .NET 4.5 and here, on this blog, you can find several posts about it. But the feature we are goint to talk about today is very exciting, because we were waiting for it more than 10 years. Since .NET 1.0 the memory limit of .NET object is 2GB. This means you cannot for example create array which contains elements with more than 2GB in total. If try to create such array, you will get the OutOfMemoryException. Let’s see an example how to produce OutOfMemoryException. Before that Open Visual Studio 2012, and create C# Console Application, like picture below. First lets create simple struct with two double members like example below: 1 2 3 4 5 6 7 8 9 10 11 12 public struct ComplexNumber {      public double Re;      public double Im;      public ComplexNumber( double re, double im)      {    ...