Builder Pattern: Step-by-Step Construction
Builder Pattern: Step-by-Step Construction
The Builder Pattern is a creational design pattern that lets you construct complex objects step-by-step. The pattern allows you to produce different types and representations of an object using the same construction code.
🏗️ The Problem
Imagine a complex User object with many optional fields (FirstName, LastName, Age, Address, PhoneNumber, etc.). A constructor with 10 parameters is hard to read and use (the “Telescoping Constructor” anti-pattern).
🚀 The .NET Implementation
In .NET, the Builder pattern is often implemented using a “Fluent Interface.”
1. The Product
public class User
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public string Email { get; set; }
}2. The Builder
public class UserBuilder
{
private readonly User _user = new User();
public UserBuilder SetName(string first, string last)
{
_user.FirstName = first;
_user.LastName = last;
return this; // Return 'this' for chaining
}
public UserBuilder SetAge(int age)
{
_user.Age = age;
return this;
}
public UserBuilder SetEmail(string email)
{
_user.Email = email;
return this;
}
public User Build() => _user;
}🛠️ Real-World Usage (Client)
// Fluent and readable construction
var user = new UserBuilder()
.SetName("John", "Doe")
.SetEmail("john@example.com")
.SetAge(30)
.Build();💡 Why use Builder?
- Readability: Clearer than a giant constructor.
- Immutability: You can make the
Userclass immutable (private setters) and only allow the Builder to create it. - Step-by-Step: You can delay some steps or run them recursively.