Suppose we have to build an object with a lot of different configurations based on a scenario. For example, we have to send an Email where we have optional properties like CC (carbon copy), BCC (blind carbon copy), attachments, etc. So the method to send an email would look somewhat like this:
As we can see there are a lot of optional properties that we might not need always. So to tackle this, we can make use of one of the famous Gang of Four (GOF) design patterns i.e. Builder Pattern.
What is a Builder Pattern?
As the name suggests, this design pattern is used to build complex objects in a step-by-step approach. Using the same construction process we can make different representations of the object.
Separate the construction of a complex object from its representation so that the same construction process can create different representations.
— Design Patterns: Elements of Reusable Object-Oriented Software
So to solve the above problem, we will put the Builder Pattern to use. We will have an EmailContent.cs
class to define properties of Email Object.
Now we will add EmailContentBuilder.cs
class to build EmailContent.cs
Now we will use the above builder class to construct EmailContent object.
And our SendEmailAsync() will look like:
So there we have it, implementing the Builder Design Pattern with fluent approach.
Any other way we could put the Builder pattern to use? Let me know in the comments below. Also, check out my other blog on Template Method Design Pattern in C#