Discovering the Builder Pattern

Builder Pattern Introduction

Welcome back! So far, we've covered various creational design patterns like the Singleton Pattern, Factory Method Pattern, and Abstract Factory Pattern. These patterns have helped you control and simplify object creation in your programs. Today, we are delving into another powerful creational pattern — the Builder Pattern. This pattern allows you to construct complex objects step by step, making the creation process more manageable and modular.

Defining the Builder Pattern

The Builder Pattern is a way to create complex objects by building them step by step. It separates the process of making an object from its final look, so you can create different versions of the object using the same steps. This pattern includes several key components:

  1. Product: The complex object to be created.
  2. Builder Interface: Specifies the construction steps.
  3. Concrete Builders: Implement the construction steps for different representations.
  4. Director: Manages the construction process.

Implementing the Builder Pattern

Let's break down the implementation of the Builder Pattern in C# with an example. We will create a house using a builder class and a director to manage the construction process. This will help you see how the theoretical components interact in practice.

Here’s what we will do, step by step:

  1. Define the House class (Product):

    • This will be our complex object that needs construction.
  2. Create the HouseBuilder abstract class (Builder Interface):

    • This abstract class will include methods to set different parts of the house.
  3. Create the ConcreteHouseBuilder class (Concrete Builders):

    • This class will implement the methods of the HouseBuilder.
  4. Introduce the Director class:

    • This class will manage the overall construction process by directing the builder on how to construct the house.

Finally, we will show how to use these components to construct a house and display its details.

Defining the House Class

First, we define the House class, which will be our complex object:

C#
public class House
{
    // Properties for the attributes of the house
    public string? Foundation { get; set; }
    public string? Structure { get; set; }
    public string? Roof { get; set; }

    // Method to display the house details
    public void ShowHouse() => Console.WriteLine($"House with {Foundation}, {Structure}, and {Roof}.");
}

In this class, the House object has three main parts: the foundation, the structure, and the roof. We also have a method to display the house details.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal