Tuesday 18 March 2014

Prototype and Builder Pattern Example

What is Builder Pattern?

Builder pattern builds a complex object by using a step by step approach. Builder interface defines the steps to build the final object. This builder is independent from the objects creation process. A class that is known as Director, controls the object creation process.
Moreover, builder pattern describes a way to separate an object from its construction. The same construction method can create different representation of the object.
Builder Pattern - UML Diagram & Implementation
The UML class diagram for the implementation of the builder design pattern is given below:
The classes, interfaces and objects in the above UML class diagram are as follows:
  1. Builder
    This is an interface which is used to define all the steps to create a product
  2. ConcreteBuilder
    This is a class which implements the Builder interface to create complex product.
  3. Product
    This is a class which defines the parts of the complex object which are to be generated by the builder pattern.
  4. Director
    This is a class which is used to construct an object using the Builder interface.

  1. public interface IBuilder
  2. {
  3. void BuildPart1();
  4. void BuildPart2();
  5. void BuildPart3();
  6. Product GetProduct();
  7. }
  8. public class ConcreteBuilder : IBuilder
  9. {
  10. private Product _product = new Product();
  11. public void BuildPart1()
  12. {
  13. _product.Part1 = "Part 1";
  14. }
  15. public void BuildPart2()
  16. {
  17. _product.Part2 = "Part 2";
  18. }
  19. public void BuildPart3()
  20. {
  21. _product.Part3 = "Part 3";
  22. }
  23. public Product GetProduct()
  24. {
  25. return _product;
  26. }
  27. }
  28. public class Product
  29. {
  30. public string Part1 { get; set; }
  31. public string Part2 { get; set; }
  32. public string Part3 { get; set; }
  33. }
  34.  
  35. public class Director
  36. {
  37. public void Construct(IBuilder IBuilder)
  38. {
  39. IBuilder.BuildPart1();
  40. IBuilder.BuildPart2();
  41. IBuilder.BuildPart3();
  42. }
  43. }
Example
The classes, interfaces and objects in the above class diagram can be identified as follows:
  1. IVehicleBuilder - Builder interface
  2. HeroBuilder & HondaBuilder- Concrete Builder
  3. Vehicle- Product
  4. Vehicle Creator - Director

  1. /// <summary>
  2. /// The 'Builder' interface
  3. /// </summary>
  4. public interface IVehicleBuilder
  5. {
  6. void SetModel();
  7. void SetEngine();
  8. void SetTransmission();
  9. void SetBody();
  10. void SetAccessories();
  11.  
  12. Vehicle GetVehicle();
  13. }
  14.  
  15. /// <summary>
  16. /// The 'ConcreteBuilder1' class
  17. /// </summary>
  18. public class HeroBuilder : IVehicleBuilder
  19. {
  20. Vehicle objVehicle = new Vehicle();
  21. public void SetModel()
  22. {
  23. objVehicle.Model = "Hero";
  24. }
  25.  
  26. public void SetEngine()
  27. {
  28. objVehicle.Engine = "4 Stroke";
  29. }
  30.  
  31. public void SetTransmission()
  32. {
  33. objVehicle.Transmission = "120 km/hr";
  34. }
  35.  
  36. public void SetBody()
  37. {
  38. objVehicle.Body = "Plastic";
  39. }
  40.  
  41. public void SetAccessories()
  42. {
  43. objVehicle.Accessories.Add("Seat Cover");
  44. objVehicle.Accessories.Add("Rear Mirror");
  45. }
  46.  
  47. public Vehicle GetVehicle()
  48. {
  49. return objVehicle;
  50. }
  51. }
  52.  
  53. /// <summary>
  54. /// The 'ConcreteBuilder2' class
  55. /// </summary>
  56. public class HondaBuilder : IVehicleBuilder
  57. {
  58. Vehicle objVehicle = new Vehicle();
  59. public void SetModel()
  60. {
  61. objVehicle.Model = "Honda";
  62. }
  63.  
  64. public void SetEngine()
  65. {
  66. objVehicle.Engine = "4 Stroke";
  67. }
  68.  
  69. public void SetTransmission()
  70. {
  71. objVehicle.Transmission = "125 Km/hr";
  72. }
  73.  
  74. public void SetBody()
  75. {
  76. objVehicle.Body = "Plastic";
  77. }
  78.  
  79. public void SetAccessories()
  80. {
  81. objVehicle.Accessories.Add("Seat Cover");
  82. objVehicle.Accessories.Add("Rear Mirror");
  83. objVehicle.Accessories.Add("Helmet");
  84. }
  85.  
  86. public Vehicle GetVehicle()
  87. {
  88. return objVehicle;
  89. }
  90. }
  91.  
  92. /// <summary>
  93. /// The 'Product' class
  94. /// </summary>
  95. public class Vehicle
  96. {
  97. public string Model { get; set; }
  98. public string Engine { get; set; }
  99. public string Transmission { get; set; }
  100. public string Body { get; set; }
  101. public List<string> Accessories { get; set; }
  102.  
  103. public Vehicle()
  104. {
  105. Accessories = new List<string>();
  106. }
  107.  
  108. public void ShowInfo()
  109. {
  110. Console.WriteLine("Model: {0}", Model);
  111. Console.WriteLine("Engine: {0}", Engine);
  112. Console.WriteLine("Body: {0}", Body);
  113. Console.WriteLine("Transmission: {0}", Transmission);
  114. Console.WriteLine("Accessories:");
  115. foreach (var accessory in Accessories)
  116. {
  117. Console.WriteLine("\t{0}", accessory);
  118. }
  119. }
  120. }
  121.  
  122. /// <summary>
  123. /// The 'Director' class
  124. /// </summary>
  125. public class VehicleCreator
  126. {
  127. private readonly IVehicleBuilder objBuilder;
  128.  
  129. public VehicleCreator(IVehicleBuilder builder)
  130. {
  131. objBuilder = builder;
  132. }
  133.  
  134. public void CreateVehicle()
  135. {
  136. objBuilder.SetModel();
  137. objBuilder.SetEngine();
  138. objBuilder.SetBody();
  139. objBuilder.SetTransmission();
  140. objBuilder.SetAccessories();
  141. }
  142.  
  143. public Vehicle GetVehicle()
  144. {
  145. return objBuilder.GetVehicle();
  146. }
  147. }
  148.  
  149. /// <summary>
  150. /// Builder Design Pattern Demo
  151. /// </summary>
  152. class Program
  153. {
  154. static void Main(string[] args)
  155. {
  156. var vehicleCreator = new VehicleCreator(new HeroBuilder());
  157. vehicleCreator.CreateVehicle();
  158. var vehicle = vehicleCreator.GetVehicle();
  159. vehicle.ShowInfo();
  160.  
  161. Console.WriteLine("---------------------------------------------");
  162.  
  163. vehicleCreator = new VehicleCreator(new HondaBuilder());
  164. vehicleCreator.CreateVehicle();
  165. vehicle = vehicleCreator.GetVehicle();
  166. vehicle.ShowInfo();
  167.  
  168. Console.ReadKey();
  169. }
  170. }

  1. Need to create an object in several steps (a step by step approach).
  2. The creation of objects should be independent from the way the object's parts are assembled.
  3. Runtime control over the creation process is required.


    Prototype Design Pattern

    Prototype pattern falls under Creational Pattern of Gang of Four (GOF) Design Patterns in .Net. It is used to 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, I would like share what is Prototype pattern and how is it work?

    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:
  4. Prototype
    This is an interface which is used for the types of object that can be cloned itself.
  5. ConcretePrototype
    This is a class which implements the Prototype interface for cloning itself.

  1. public interface Prototype
  2. {
  3. Prototype Clone();
  4. }
  5. public class ConcretePrototypeA : Prototype
  6. {
  7. public Prototype Clone()
  8. {
  9. // Shallow Copy: only top-level objects are duplicated
  10. return (Prototype)MemberwiseClone();
  11. // Deep Copy: all objects are duplicated
  12. //return (Prototype)this.Clone();
  13. }
  14. }
  15.  
  16. public class ConcretePrototypeB : Prototype
  17. {
  18. public Prototype Clone()
  19. {
  20. // Shallow Copy: only top-level objects are duplicated
  21. return (Prototype)MemberwiseClone();
  22. // Deep Copy: all objects are duplicated
  23. //return (Prototype)this.Clone();
  24. }
  25. }
 Example
The classes, interfaces and objects in the above class diagram can be identified as follows:
  1. IEmployee - Prototype interface
  2. Developer & Typist- Concrete Prototype

  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. }

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

1 comment: