Design Pattern – Builder

According to Gang of Four, a creational pattern “Builder” allows to separate and reuse a specific method to build something.


Use Case

Lets us take an example of a Car, and the user wanted to build two models, i.e., SUV and Sedan. Builder design pattern comes in handy in the above use case, and let’s see a step-by-step demonstration.


And the Car class has the following properties.

public class Car{
 public string Name { get; set; }
 public double TopSpeed { get; set; }
 public bool IsSUV { get; set; }
}

Prerequisites

  1. Basic knowledge of OOPS concepts.

  2. Any programming language knowledge.

The article demonstrates the usage of builder design patterns using the C# programming language. So, to begin with, C#

View at Medium.com


Learning Objectives

  1. How to code using a builder design pattern?



Getting Started

Firstly, let’s implement an abstract class builder extended by different car models like SUV or Sedan as per use case.


The abstract class consists of the following methods

  1. Abstract methods for each property of the Car class.

  2. A virtual method that outputs the Car class instance.

Now, let’s create a factory that utilizes CarBuilder class to build different car models and returns the instance of the car made.


Finally, implement different models of cars.

ModelSuv.cs



ModelSedan.cs

How to user builder pattern from the Main() method

Finally, let’s use design patterns to build different car models with the help of factory.Build(<model>) method.

The above usage shows how gracefully we can build different car models using the builder design pattern. The code pattern is highly maintainable & extensible. If in the future if we need to develop a new model, just the new model needs to extend the CarBuilder class, and it’s done.


Output

Github Repo

The following repository shows the above use case implementation using a Builder Design Pattern in the console-based application.

https://github.com/ssukhpinder/BuilderPattern





Thank you for reading, and I hope you liked the article. Please provide your feedback in the comment section.


Follow me on

C# Publication, LinkedIn, Instagram, Twitter, Dev.to, Pinterest, Substack, Wix.

Recent Posts

See All

Design Pattern – Adapter

#Aspnetcore #AdapterDesignPattern #Csharp #DesignPatterns #Dotnet According to Gang of Four, the Adapter Pattern converts the interfaces of a class into interfaces that the client requires. In other w