Monday, October 12, 2015

Improve the knowledge about Builder Design Patterns

Builder

Definition
Separate the construction of a complex object from its representation so that the same construction process can create different representations.




UML class diagram








Participants


    The classes and objects participating in this pattern are:
  • Builder  (VehicleBuilder)
    • specifies an abstract interface for creating parts of a Product object
  • ConcreteBuilder  (MotorCycleBuilder, CarBuilder, ScooterBuilder)
    • constructs and assembles parts of the product by implementing the Builder interface
    • defines and keeps track of the representation it creates
    • provides an interface for retrieving the product
  • Director  (Shop)
    • constructs an object using the Builder interface
  • Product  (Vehicle)
    • represents the complex object under construction. ConcreteBuilder builds the product's internal representation and defines the process by which it's assembled
    • includes classes that define the constituent parts, including interfaces for assembling the parts into the final result





Structural code in C#


This structural code demonstrates the Builder pattern in which complex objects are created in a step-by-step fashion. The construction process can create different object representations and provides a high level of control over the assembly of the objects.
1.                   
2.   
3.  using System;
4.  using System.Collections.Generic;
5.   
6.  namespace DoFactory.GangOfFour.Builder.Structural
7.  {
8.    /// <summary>
9.    /// MainApp startup class for Structural
10.   /// Builder Design Pattern.
11.   /// </summary>
12.   public class MainApp
13.   {
14.     /// <summary>
15.     /// Entry point into console application.
16.     /// </summary>
17.     public static void Main()
18.     {
19.       // Create director and builders
20.       Director director = new Director();
21.  
22.       Builder b1 = new ConcreteBuilder1();
23.       Builder b2 = new ConcreteBuilder2();
24.  
25.       // Construct two products
26.       director.Construct(b1);
27.       Product p1 = b1.GetResult();
28.       p1.Show();
29.  
30.       director.Construct(b2);
31.       Product p2 = b2.GetResult();
32.       p2.Show();
33.  
34.       // Wait for user
35.       Console.ReadKey();
36.     }
37.   }
38.  
39.   /// <summary>
40.   /// The 'Director' class
41.   /// </summary>
42.   class Director
43.   {
44.     // Builder uses a complex series of steps
45.     public void Construct(Builder builder)
46.     {
47.       builder.BuildPartA();
48.       builder.BuildPartB();
49.     }
50.   }
51.  
52.   /// <summary>
53.   /// The 'Builder' abstract class
54.   /// </summary>
55.   abstract class Builder
56.   {
57.     public abstract void BuildPartA();
58.     public abstract void BuildPartB();
59.     public abstract Product GetResult();
60.   }
61.  
62.   /// <summary>
63.   /// The 'ConcreteBuilder1' class
64.   /// </summary>
65.   class ConcreteBuilder1 : Builder
66.   {
67.     private Product _product = new Product();
68.  
69.     public override void BuildPartA()
70.     {
71.       _product.Add("PartA");
72.     }
73.  
74.     public override void BuildPartB()
75.     {
76.       _product.Add("PartB");
77.     }
78.  
79.     public override Product GetResult()
80.     {
81.       return _product;
82.     }
83.   }
84.  
85.   /// <summary>
86.   /// The 'ConcreteBuilder2' class
87.   /// </summary>
88.   class ConcreteBuilder2 : Builder
89.   {
90.     private Product _product = new Product();
91.  
92.     public override void BuildPartA()
93.     {
94.       _product.Add("PartX");
95.     }
96.  
97.     public override void BuildPartB()
98.     {
99.       _product.Add("PartY");
100.                }
101.             
102.                public override Product GetResult()
103.                {
104.                  return _product;
105.                }
106.              }
107.             
108.              /// <summary>
109.              /// The 'Product' class
110.              /// </summary>
111.              class Product
112.              {
113.                private List<string> _parts = new List<string>();
114.             
115.                public void Add(string part)
116.                {
117.                  _parts.Add(part);
118.                }
119.             
120.                public void Show()
121.                {
122.                  Console.WriteLine("\nProduct Parts -------");
123.                  foreach (string part in _parts)
124.                    Console.WriteLine(part);
125.                }
126.              }
127.            }
128.             
129.             
130.                    
131.                        


Output
Product Parts -------
PartA
PartB

Product Parts -------
PartX
PartY






Real-world code in C#


This real-world code demonstates the Builder pattern in which different vehicles are assembled in a step-by-step fashion. The Shop uses VehicleBuilders to construct a variety of Vehicles in a series of sequential steps.
1.                   
2.     
3.  using System;
4.  using System.Collections.Generic;
5.   
6.  namespace DoFactory.GangOfFour.Builder.RealWorld
7.  {
8.    /// <summary>
9.    /// MainApp startup class for Real-World
10.   /// Builder Design Pattern.
11.   /// </summary>
12.   public class MainApp
13.   {
14.     /// <summary>
15.     /// Entry point into console application.
16.     /// </summary>
17.     public static void Main()
18.     {
19.       VehicleBuilder builder;
20.  
21.       // Create shop with vehicle builders
22.       Shop shop = new Shop();
23.  
24.       // Construct and display vehicles
25.       builder = new ScooterBuilder();
26.       shop.Construct(builder);
27.       builder.Vehicle.Show();
28.  
29.       builder = new CarBuilder();
30.       shop.Construct(builder);
31.       builder.Vehicle.Show();
32.  
33.       builder = new MotorCycleBuilder();
34.       shop.Construct(builder);
35.       builder.Vehicle.Show();
36.  
37.       // Wait for user
38.       Console.ReadKey();
39.     }
40.   }
41.  
42.   /// <summary>
43.   /// The 'Director' class
44.   /// </summary>
45.   class Shop
46.   {
47.     // Builder uses a complex series of steps
48.     public void Construct(VehicleBuilder vehicleBuilder)
49.     {
50.       vehicleBuilder.BuildFrame();
51.       vehicleBuilder.BuildEngine();
52.       vehicleBuilder.BuildWheels();
53.       vehicleBuilder.BuildDoors();
54.     }
55.   }
56.  
57.   /// <summary>
58.   /// The 'Builder' abstract class
59.   /// </summary>
60.   abstract class VehicleBuilder
61.   {
62.     protected Vehicle vehicle;
63.  
64.     // Gets vehicle instance
65.     public Vehicle Vehicle
66.     {
67.       get { return vehicle; }
68.     }
69.  
70.     // Abstract build methods
71.     public abstract void BuildFrame();
72.     public abstract void BuildEngine();
73.     public abstract void BuildWheels();
74.     public abstract void BuildDoors();
75.   }
76.  
77.   /// <summary>
78.   /// The 'ConcreteBuilder1' class
79.   /// </summary>
80.   class MotorCycleBuilder : VehicleBuilder
81.   {
82.     public MotorCycleBuilder()
83.     {
84.       vehicle = new Vehicle("MotorCycle");
85.     }
86.  
87.     public override void BuildFrame()
88.     {
89.       vehicle["frame"] = "MotorCycle Frame";
90.     }
91.  
92.     public override void BuildEngine()
93.     {
94.       vehicle["engine"] = "500 cc";
95.     }
96.  
97.     public override void BuildWheels()
98.     {
99.       vehicle["wheels"] = "2";
100.                }
101.             
102.                public override void BuildDoors()
103.                {
104.                  vehicle["doors"] = "0";
105.                }
106.              }
107.             
108.             
109.              /// <summary>
110.              /// The 'ConcreteBuilder2' class
111.              /// </summary>
112.              class CarBuilder : VehicleBuilder
113.              {
114.                public CarBuilder()
115.                {
116.                  vehicle = new Vehicle("Car");
117.                }
118.             
119.                public override void BuildFrame()
120.                {
121.                  vehicle["frame"] = "Car Frame";
122.                }
123.             
124.                public override void BuildEngine()
125.                {
126.                  vehicle["engine"] = "2500 cc";
127.                }
128.             
129.                public override void BuildWheels()
130.                {
131.                  vehicle["wheels"] = "4";
132.                }
133.             
134.                public override void BuildDoors()
135.                {
136.                  vehicle["doors"] = "4";
137.                }
138.              }
139.             
140.              /// <summary>
141.              /// The 'ConcreteBuilder3' class
142.              /// </summary>
143.              class ScooterBuilder : VehicleBuilder
144.              {
145.                public ScooterBuilder()
146.                {
147.                  vehicle = new Vehicle("Scooter");
148.                }
149.             
150.                public override void BuildFrame()
151.                {
152.                  vehicle["frame"] = "Scooter Frame";
153.                }
154.             
155.                public override void BuildEngine()
156.                {
157.                  vehicle["engine"] = "50 cc";
158.                }
159.             
160.                public override void BuildWheels()
161.                {
162.                  vehicle["wheels"] = "2";
163.                }
164.             
165.                public override void BuildDoors()
166.                {
167.                  vehicle["doors"] = "0";
168.                }
169.              }
170.             
171.              /// <summary>
172.              /// The 'Product' class
173.              /// </summary>
174.              class Vehicle
175.              {
176.                private string _vehicleType;
177.                private Dictionary<string,string> _parts =
178.                  new Dictionary<string,string>();
179.             
180.                // Constructor
181.                public Vehicle(string vehicleType)
182.                {
183.                  this._vehicleType = vehicleType;
184.                }
185.             
186.                // Indexer
187.                public string this[string key]
188.                {
189.                  get { return _parts[key]; }
190.                  set { _parts[key] = value; }
191.                }
192.             
193.                public void Show()
194.                {
195.                  Console.WriteLine("\n---------------------------");
196.                  Console.WriteLine("Vehicle Type: {0}", _vehicleType);
197.                  Console.WriteLine(" Frame : {0}", _parts["frame"]);
198.                  Console.WriteLine(" Engine : {0}", _parts["engine"]);
199.                  Console.WriteLine(" #Wheels: {0}", _parts["wheels"]);
200.                  Console.WriteLine(" #Doors : {0}", _parts["doors"]);
201.                }
202.              }
203.            }
204.             
205.             
206.             
207.                    
208.                        


Output
---------------------------
Vehicle Type: Scooter
 Frame  : Scooter Frame
 Engine : none
 #Wheels: 2
 #Doors : 0

---------------------------
Vehicle Type: Car
 Frame  : Car Frame
 Engine : 2500 cc
 #Wheels: 4
 #Doors : 4

---------------------------
Vehicle Type: MotorCycle
 Frame  : MotorCycle Frame
 Engine : 500 cc
 #Wheels: 2
 #Doors : 0


No comments:

Post a Comment