HI WELCOME TO SIRIS
Showing posts with label Design Pattern. Show all posts
Showing posts with label Design Pattern. Show all posts

Bridge Design Pattern - C#

Bridge pattern falls under Structural Pattern of Gang of Four (GOF) Design Patterns in .Net. All we know, Inheritance is a way to specify different implementations of an abstraction. But in this way, implementations are tightly bound to the abstraction and can not be modified independently. The Bridge pattern provides an alternative to inheritance when there are more than one version of an abstraction. In this article, I would like share what is bridge pattern and how is it work?

What is Bridge Pattern

Bridge pattern is used to separate an abstraction from its implementation so that both can be modified independently.
This pattern involves an interface which acts as a bridge between the abstraction class and implementer classes and also makes the functionality of implementer class independent from the abstraction class. Both types of classes can be modified without affecting to each other.

Bridge Pattern - UML Diagram & Implementation

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


  1. Abstraction

    This is an abstract class and containing members that define an abstract business object and its functionality. It contains a reference to an object of type Bridge. It can also acts as the base class for other abstractions.
  2. Redefined Abstraction

    This is a class which inherits from the Abstraction class. It extends the interface defined by Abstraction class.
  3. Bridge

    This is an interface which acts as a bridge between the abstraction class and implementer classes and also makes the functionality of implementer class independent from the abstraction class.
  4. ImplementationA & ImplementationB

    These are classes which implement the Bridge interface and also provide the implementation details for the associated Abstraction class.

C# - Implementation Code

  1. public abstract class Abstraction
  2. {
  3. public Bridge Implementer { get; set; }
  4. public virtual void Operation()
  5. {
  6. Console.WriteLine("ImplementationBase:Operation()");
  7. Implementer.OperationImplementation();
  8. }
  9. }
  10. public class RefinedAbstraction : Abstraction
  11. {
  12. public override void Operation()
  13. {
  14. Console.WriteLine("RefinedAbstraction:Operation()");
  15. Implementer.OperationImplementation();
  16. }
  17. }
  18. public interface Bridge
  19. {
  20. void OperationImplementation();
  21. }
  22. public class ImplementationA : Bridge
  23. {
  24. public void OperationImplementation()
  25. {
  26. Console.WriteLine("ImplementationA:OperationImplementation()");
  27. }
  28. }
  29. public class ImplementationB : Bridge
  30. {
  31. public void OperationImplementation()
  32. {
  33. Console.WriteLine("ImplementationB:OperationImplementation()");
  34. }
  35. }

Bridge Pattern - Example


Who is what?

The classes, interfaces and objects in the above class diagram can be identified as follows:
  1. Message - Abstraction Class.
  2. SystemMessage & UserMessage- Redefined Abstraction Classes.
  3. IMessageSender- Bridge Interface.
  4. EmailSender, WebServiceSender & MSMQ Sender- ConcreteImplementation class which implements the IMessageSender interface.

C# - Sample Code

  1. /// <summary>
  2. /// The 'Abstraction' class
  3. /// </summary>
  4. public abstract class Message
  5. {
  6. public IMessageSender MessageSender { get; set; }
  7. public string Subject { get; set; }
  8. public string Body { get; set; }
  9. public abstract void Send();
  10. }
  11.  
  12. /// <summary>
  13. /// The 'RefinedAbstraction' class
  14. /// </summary>
  15. public class SystemMessage : Message
  16. {
  17. public override void Send()
  18. {
  19. MessageSender.SendMessage(Subject, Body);
  20. }
  21. }
  22.  
  23. /// <summary>
  24. /// The 'RefinedAbstraction' class
  25. /// </summary>
  26. public class UserMessage : Message
  27. {
  28. public string UserComments { get; set; }
  29.  
  30. public override void Send()
  31. {
  32. string fullBody = string.Format("{0}\nUser Comments: {1}", Body, UserComments);
  33. MessageSender.SendMessage(Subject, fullBody);
  34. }
  35. }
  36.  
  37. /// <summary>
  38. /// The 'Bridge/Implementor' interface
  39. /// </summary>
  40. public interface IMessageSender
  41. {
  42. void SendMessage(string subject, string body);
  43. }
  44.  
  45. /// <summary>
  46. /// The 'ConcreteImplementor' class
  47. /// </summary>
  48. public class EmailSender : IMessageSender
  49. {
  50. public void SendMessage(string subject, string body)
  51. {
  52. Console.WriteLine("Email\n{0}\n{1}\n", subject, body);
  53. }
  54. }
  55.  
  56. /// <summary>
  57. /// The 'ConcreteImplementor' class
  58. /// </summary>
  59. public class MSMQSender : IMessageSender
  60. {
  61. public void SendMessage(string subject, string body)
  62. {
  63. Console.WriteLine("MSMQ\n{0}\n{1}\n", subject, body);
  64. }
  65. }
  66.  
  67. /// <summary>
  68. /// The 'ConcreteImplementor' class
  69. /// </summary>
  70. public class WebServiceSender : IMessageSender
  71. {
  72. public void SendMessage(string subject, string body)
  73. {
  74. Console.WriteLine("Web Service\n{0}\n{1}\n", subject, body);
  75. }
  76. }
  77.  
  78. /// <summary>
  79. /// Bridge Design Pattern Demo
  80. /// </summary>
  81. class Program
  82. {
  83. static void Main(string[] args)
  84. {
  85. IMessageSender email = new EmailSender();
  86. IMessageSender queue = new MSMQSender();
  87. IMessageSender web = new WebServiceSender();
  88.  
  89. Message message = new SystemMessage();
  90. message.Subject = "Test Message";
  91. message.Body = "Hi, This is a Test Message";
  92. message.MessageSender = email;
  93. message.Send();
  94.  
  95. message.MessageSender = queue;
  96. message.Send();
  97.  
  98. message.MessageSender = web;
  99. message.Send();
  100.  
  101. UserMessage usermsg = new UserMessage();
  102. usermsg.Subject = "Test Message";
  103. usermsg.Body = "Hi, This is a Test Message";
  104. usermsg.UserComments = "I hope you are well";
  105.  
  106. usermsg.MessageSender = email;
  107. usermsg.Send();
  108.  
  109. Console.ReadKey();
  110. }
  111. }

Bridge Pattern Demo - Output

When to use it?

  1. Abstractions and implementations should be modified independently.
  2. Changes in the implementation of an abstraction should have no impact on clients.
  3. The Bridge pattern is used when a new version of a software or system is brought out, but the older version of the software still running for its existing client. There is no need to change the client code, but the client need to choose which version he wants to use.

Note

Bridge pattern has nearly the same structure as the Adapter Pattern. But it is used when designing new systems instead of the Adapter pattern which is used with already existing systems.
What do you think?
I hope you will enjoy the bridge Pattern while designing your software. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

Adapter Design Pattern - C#

Adapter pattern falls under Structural Pattern of Gang of Four (GOF) Design Patterns in .Net. The Adapter pattern allows a system to use classes of another system that is incompatible with it. It is especially used for toolkits and libraries. In this article, I would like share what is adapter pattern and how is it work?

What is Adapter Pattern

Adapter pattern acts as a bridge between two incompatible interfaces. This pattern involves a single class called adapter which is responsible for communication between two independent or incompatible interfaces.
For Example: A card reader acts as an adapter between memory card and a laptop. You plugins the memory card into card reader and card reader into the laptop so that memory card can be read via laptop.

Adapter Pattern - UML Diagram & Implementation

The UML class diagram for the implementation of the Adapter design pattern is given below:



The classes, interfaces and objects in the above UML class diagram are as follows:
  1. ITarget

    This is an interface which is used by the client to achieve its functionality/request.
  2. Adapter

    This is a class which implements the ITarget interface and inherits the Adaptee class. It is responsible for communication between Client and Adaptee.
  3. Adaptee

    This is a class which have the functionality, required by the client. However, its interface is not compatible with the client.
  4. Client

    This is a class which interact with a type that implements the ITarget interface. However, the communication class called adaptee, is not compatible with the client

C# - Implementation Code

  1. public class Client
  2. {
  3. private ITarget target;
  4.  
  5. public Client(ITarget target)
  6. {
  7. this.target = target;
  8. }
  9.  
  10. public void MakeRequest()
  11. {
  12. target.MethodA();
  13. }
  14. }
  15.  
  16. public interface ITarget
  17. {
  18. void MethodA();
  19. }
  20.  
  21. public class Adapter : Adaptee, ITarget
  22. {
  23. public void MethodA()
  24. {
  25. MethodB();
  26. }
  27. }
  28.  
  29. public class Adaptee
  30. {
  31. public void MethodB()
  32. {
  33. Console.WriteLine("MethodB() is called");
  34. }
  35. }

Adapter Pattern - Example


Who is what?

The classes, interfaces and objects in the above class diagram can be identified as follows:
  1. ITraget - Target interface
  2. Employee Adapter- Adapter Class
  3. HR System- Adaptee Class
  4. ThirdPartyBillingSystem - Client

C# - Sample Code

  1. /// <summary>
  2. /// The 'Client' class
  3. /// </summary>
  4. public class ThirdPartyBillingSystem
  5. {
  6. private ITarget employeeSource;
  7. public ThirdPartyBillingSystem(ITarget employeeSource)
  8. {
  9. this.employeeSource = employeeSource;
  10. }
  11. public void ShowEmployeeList()
  12. {
  13. List<string> employee = employeeSource.GetEmployeeList();
  14. //To DO: Implement you business logic
  15. Console.WriteLine("######### Employee List ##########");
  16. foreach (var item in employee)
  17. {
  18. Console.Write(item);
  19. }
  20. }
  21. }
  22.  
  23. /// <summary>
  24. /// The 'ITarget' interface
  25. /// </summary>
  26. public interface ITarget
  27. {
  28. List<string> GetEmployeeList();
  29. }
  30.  
  31. /// <summary>
  32. /// The 'Adaptee' class
  33. /// </summary>
  34. public class HRSystem
  35. {
  36. public string[][] GetEmployees()
  37. {
  38. string[][] employees = new string[4][];
  39. employees[0] = new string[] { "100", "Deepak", "Team Leader" };
  40. employees[1] = new string[] { "101", "Rohit", "Developer" };
  41. employees[2] = new string[] { "102", "Gautam", "Developer" };
  42. employees[3] = new string[] { "103", "Dev", "Tester" };
  43. return employees;
  44. }
  45. }
  46.  
  47. /// <summary>
  48. /// The 'Adapter' class
  49. /// </summary>
  50. public class EmployeeAdapter : HRSystem, ITarget
  51. {
  52. public List<string> GetEmployeeList()
  53. {
  54. List<string> employeeList = new List<string>();
  55. string[][] employees = GetEmployees();
  56. foreach (string[] employee in employees)
  57. {
  58. employeeList.Add(employee[0]);
  59. employeeList.Add(",");
  60. employeeList.Add(employee[1]);
  61. employeeList.Add(",");
  62. employeeList.Add(employee[2]);
  63. employeeList.Add("\n");
  64. }
  65. return employeeList;
  66. }
  67. }
  68.  
  69. ///
  70. /// Adapter Design Pattern Demo
  71. ///
  72. class Program
  73. {
  74. static void Main(string[] args)
  75. {
  76. ITarget Itarget = new EmployeeAdapter();
  77. ThirdPartyBillingSystem client = new ThirdPartyBillingSystem(Itarget);
  78. client.ShowEmployeeList();
  79. Console.ReadKey();
  80. }
  81. }

Adapter Pattern Demo - Output

When to use it?

  1. Allow a system to use classes of another system that is incompatible with it.
  2. Allow communication between new and already existing system which are independent to each other
  3. Ado.Net SqlAdapter, OracleAdapter, MySqlAdapter are best example of Adapter Pattern.

Note

  1. Internally, Adapter use Factory design pattern for creating objects. But it can also use Builder design pattern and prototype design pattern for creating product. It completely depends upon your implementation for creating products.
  2. Adapter can be used as an alternative to Facade to hide platform-specific classes.
  3. When Adapter, Builder, and Prototype define a factory for creating the products, we should consider the following points :
    1. Adapter use the factory for creating objects of several classes.
    2. Builder use the factory for creating a complex product by using simple objects and a step by step approach.
    3. Prototype use the factory for building a product by copying an existing product.
What do you think?
I hope you will enjoy the Adapter Pattern while designing your software. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

Singleton Design Pattern - C#

Singleton pattern falls under Creational Pattern of Gang of Four (GOF) Design Patterns in .Net. It is pattern is one of the simplest design patterns. This pattern ensures that a class has only one instance. In this article, I would like share what is Singleton pattern and how is it work?

What is Singleton Pattern?

Singleton pattern is one of the simplest design patterns. This pattern ensures that a class has only one instance and provides a global point of access to it.

Singleton Pattern - UML Diagram & Implementation

The UML class diagram for the implementation of the Singleton design pattern is given below:



The classes, and objects in the above UML class diagram are as follows:
  1. Singleton

    This is a class which is responsible for creating and maintaining its own unique instance.

C# - Implementation Code

  1. //eager initialization of singleton
  2. public class Singleton
  3. {
  4. private static Singleton instance = new Singleton();
  5. private Singleton() { }
  6.  
  7. public static Singleton GetInstance
  8. {
  9. get
  10. {
  11. return instance;
  12. }
  13. }
  14. }
  15.  
  16. ////lazy initialization of singleton
  17. public class Singleton
  18. {
  19. private static Singleton instance = null;
  20. private Singleton() { }
  21.  
  22. public static Singleton GetInstance
  23. {
  24. get
  25. {
  26. if (instance == null)
  27. instance = new Singleton();
  28.  
  29. return instance;
  30. }
  31. }
  32. }
  33.  
  34. ////Thread-safe (Double-checked Locking) initialization of singleton
  35. public class Singleton
  36. {
  37. private static Singleton instance = null;
  38. private Singleton() { }
  39. private static object lockThis = new object();
  40.  
  41. public static Singleton GetInstance
  42. {
  43. get
  44. {
  45. lock (lockThis)
  46. {
  47. if (instance == null)
  48. instance = new Singleton();
  49.  
  50. return instance;
  51. }
  52. }
  53. }
  54. }

Singleton Pattern - Example


Who is what?

The classes and objects in the above class diagram can be identified as follows:
  1. Singleton - Singleton class

C# - Sample Code

  1. /// <summary>
  2. /// The 'Singleton' class
  3. /// </summary>
  4. public class Singleton
  5. {
  6. // .NET guarantees thread safety for static initialization
  7. private static Singleton instance = null;
  8. private string Name{get;set;}
  9. private string IP{get;set;}
  10. private Singleton()
  11. {
  12. //To DO: Remove below line
  13. Console.WriteLine("Singleton Intance");
  14.  
  15. Name = "Server1";
  16. IP = "192.168.1.23";
  17. }
  18. // Lock synchronization object
  19. private static object syncLock = new object();
  20.  
  21. public static Singleton Instance
  22. {
  23. get
  24. {
  25. // Support multithreaded applications through
  26. // 'Double checked locking' pattern which (once
  27. // the instance exists) avoids locking each
  28. // time the method is invoked
  29. lock (syncLock)
  30. {
  31. if (Singleton.instance == null)
  32. Singleton.instance = new Singleton();
  33.  
  34. return Singleton.instance;
  35. }
  36. }
  37. }
  38.  
  39. public void Show()
  40. {
  41. Console.WriteLine("Server Information is : Name={0} & IP={1}", IP, Name);
  42. }
  43.  
  44. }
  45.  
  46. /// <summary>
  47. /// Singleton Pattern Demo
  48. /// </summary>
  49. ///
  50. class Program
  51. {
  52. static void Main(string[] args)
  53. {
  54. Singleton.Instance.Show();
  55. Singleton.Instance.Show();
  56.  
  57. Console.ReadKey();
  58. }
  59. }

Singleton Pattern Demo - Output

When to use it?

  1. Exactly one instance of a class is required.
  2. Controlled access to a single object is necessary.
What do you think?
I hope you will enjoy the Singleton Pattern while designing your software. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

Prototype Design Pattern - C#

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?

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

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.
What do you think?
I hope you will enjoy the Prototype Pattern while designing your software. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

Builder Design Pattern - C#

Builder pattern falls under Creational Pattern of Gang of Four (GOF) Design Patterns in .Net. It is used to builds a complex object by using a step by step approach. It provides an interface for creating parts of a product. In this article, I would like share what is builder pattern and how is it work?

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.

C# - Implementation Code

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

Builder Pattern - Example


Who is what?

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

C# - Sample Code

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

Builder Pattern Demo - Output

When to use it?

  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.
What do you think?
I hope you will enjoy the Builder Pattern while designing your software. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.