Monday, December 4, 2023

Builder Design Pattern in C#

What is the Builder Design Pattern?

The Builder Design Pattern is a creational design pattern that helps in constructing complex objects step by step. It separates the construction of an object from its representation, allowing the same construction process to create different representations. In C#, the Builder pattern is widely used to create objects with varying configurations while keeping the construction process unchanged.

The key idea is to separate the construction of a complex object from its representation, allowing the same construction process to create different representations.

So, the Builder Design Pattern is all about separating the construction process from its representation. When the construction process of your object is very complex, only you need to use the Builder Design Pattern.

COmponents of Builder Design Pattern

  • Abstract Builder: The Builder is an interface defining all the steps to make the concrete product.
  • Concrete Builder: The Concrete Builder Classes implements the Abstract Builder interface and provides implementation to all the abstract methods. The Concrete Builder is responsible for constructing and assembling the individual parts of the product by implementing the Builder interface. It also defines and tracks the representation it creates.
  • Director: The Director takes those individual processes from the Builder and defines the sequence to build the product.
  • Product: The Product is a class, and we want to create this product object using the builder design pattern. This class defines different parts that will make the product.

Let's dive into an example to illustrate the implementation of the Builder pattern in C#:

Consider a scenario where we need to build a Meal object, consisting of different components like a burger, drink, fries, and a dessert. The Builder pattern can assist in constructing a Meal object by using a MealBuilder.

  1. Creating the Product:Create a class file named Meal.cs and copy and paste the following code. This is our product class.
        /// <summary>
        /// Represents the object that is being constructed
        /// </summary>
        public class Meal
        {
            public string Burger { get; set; }
            public string Drink { get; set; }
            public string Fries { get; set; }
            public string Dessert { get; set; }
    
            public void Display()
            {
                Console.WriteLine($"Burger: {Burger}, Drink: {Drink}, Fries: {Fries}, Dessert: {Dessert}");
            }
        }
        
  2. Creating the Abstract Builder:Create a interface file named IMealBuilder.cs and then copy and paste the following. This interface will provide the blueprint to create different types of products.
        /// <summary>
        /// Abstract interface defining the steps for building the object
        /// </summary>
        public interface IMealBuilder
        {
            void AddBurger(string burger);
            void AddDrink(string drink);
            void AddFries(string fries);
            void AddDessert(string dessert);
            Meal GetMeal();
        }
        
  3. Creating Concrete Builder Classes:The Concrete Builder classes follow the Builder interface and provide specific implementations of the building steps.Create a class file named ConcreteMealBuilder.cs and then copy and paste the following.
        /// <summary>
        /// Implements the Builder interface to build the product
        /// </summary>
        public class ConcreteMealBuilder : IMealBuilder
        {
            private Meal _meal = new Meal();
    
            public void AddBurger(string burger)
            {
                _meal.Burger = burger;
            }
    
            public void AddDrink(string drink)
            {
                _meal.Drink = drink;
            }
    
            public void AddFries(string fries)
            {
                _meal.Fries = fries;
            }
    
            public void AddDessert(string dessert)
            {
                _meal.Dessert = dessert;
            }
    
            public Meal GetMeal()
            {
                return _meal;
            }
        }
        
  4. Creating the Director:The Director Class in Builder Design Pattern is only responsible for executing the building steps in order. These steps are so generic that these steps will produce different products. It is helpful when producing products according to a specific order or configuration.Create a class file named MealDirector.cs and then copy and paste the following.
        /// <summary>
        /// Manages the building process using the Builder
        /// </summary>
        public class MealDirector
        {
            public Meal Construct(IMealBuilder builder)
            {
                builder.AddBurger("Cheeseburger");
                builder.AddDrink("Cola");
                builder.AddFries("Large fries");
                builder.AddDessert("Ice cream");
    
                return builder.GetMeal();
            }
        }
        
  5. Client Code:The client code in the Builder Design Pattern will create a builder object, then pass that builder object to the director, and then the director will initiate the construction process. The end result is nothing but the product that is retrieved from the builder object.In our example, the Main method of the Program class is going to be the Client.
        using BuilderDesignPattern.Builder;
        using BuilderDesignPattern.Director;
        using BuilderDesignPattern.Product;
    
        MealDirector director = new MealDirector();
        IMealBuilder builder = new ConcreteMealBuilder();
    
        Meal meal = director.Construct(builder);
        meal.Display();
        Console.ReadKey();
        

Output

builder design pattern output

By using the Builder pattern, we can create different variations of meals by simply creating different concrete builders while keeping the construction process consistent.

Understanding and implementing the Builder pattern in C# enables flexible and scalable object construction while maintaining clear separation between the construction process and the resulting object.

The full source code is available here:

Happy coding!! 😊

No comments:

Post a Comment

^ Scroll to Top