Understanding Builder Design Pattern

Introduction

In this article, we will cover the Builder Design Pattern.

What is a Builder?

It's a creational pattern that separates the construction of a complex object from its representation. In simpler terms, it allows you to construct objects step by step, controlling every aspect of their creation.

Why User Builder?

Imagine dealing with an object that requires numerous parameters to be set during its construction. The Builder Pattern comes to the rescue by providing a clean and flexible solution, eliminating the need for multiple constructors or telescoping constructors.

Where to Use Builder?

Anywhere you need to create complex objects with varying configurations! Whether it's building user profiles, crafting customized orders, or constructing intricate game characters, the Builder Pattern shines in scenarios where object creation involves multiple steps and options.

Real-Time Example of Builder Design Pattern Travel Agency where Users can Customize Holiday Packages.

Let’s consider a scenario for a travel agency where users can customize holiday packages. A typical holiday package might include flights, hotel bookings, car rentals, and excursions. Not every user will select all components, but the package should be flexible to accommodate various choices

using System;
using System.Collections.Generic;
using System.Linq;
namespace BuilderDesignPattern
{
    // Product: HolidayPackage
    public class HolidayPackage
    {
        public string Flight { get; set; }
        public string Hotel { get; set; }
        public string CarRental { get; set; }
        public List<string> Excursions { get; private set; } = new List<string>();

        public void DisplayPackageDetails()
        {
            Console.WriteLine($"Flight: {Flight ?? "Not selected"}");
            Console.WriteLine($"Hotel: {Hotel ?? "Not selected"}");
            Console.WriteLine($"Car Rental: {CarRental ?? "Not selected"}");
            Console.WriteLine("Excursions: " + (Excursions.Any() ? string.Join(", ", Excursions) : "No excursions selected"));
        }
    }
    // Builder (Abstract Builder)
    public abstract class HolidayPackageBuilder
    {
        protected HolidayPackage Package { get; private set; } = new HolidayPackage();

        public abstract void BookFlight(string flightDetails);
        public abstract void BookHotel(string hotelName);
        public abstract void RentCar(string carDetails);
        public abstract void AddExcursion(string excursion);

        public HolidayPackage GetPackage() => Package;
    }
    // Concrete Builder: CustomHolidayPackageBuilder
    public class CustomHolidayPackageBuilder : HolidayPackageBuilder
    {
        public override void BookFlight(string flightDetails)
        {
            Package.Flight = flightDetails;
        }
        public override void BookHotel(string hotelName)
        {
            Package.Hotel = hotelName;
        }
        public override void RentCar(string carDetails)
        {
            Package.CarRental = carDetails;
        }
        public override void AddExcursion(string excursion)
        {
            Package.Excursions.Add(excursion);
        }
    }
    // Director: TravelAgent
    public class TravelAgent
    {
        public void CreatePackage(HolidayPackageBuilder builder, bool wantsFlight, bool wantsHotel, bool wantsCar, IEnumerable<string> excursions)
        {
            if (wantsFlight) builder.BookFlight("Flight details...");
            if (wantsHotel) builder.BookHotel("XYZ Hotel");
            if (wantsCar) builder.RentCar("SUV Model XYZ");
            foreach (var excursion in excursions)
            {
                builder.AddExcursion(excursion);
            }
        }
    }
    // Client Code
    // Testing the Builder Design Pattern
    public class Program
    {
        public static void Main()
        {
            var travelAgent = new TravelAgent();
            var packageBuilder = new CustomHolidayPackageBuilder();

            travelAgent.CreatePackage(packageBuilder, true, true, true, new[] { "Beach trip", "Sightseeing" });

            var holidayPackage = packageBuilder.GetPackage();
            holidayPackage.DisplayPackageDetails();

            Console.ReadKey();
        }
    }
}

Output


Similar Articles