What is Builder Pattern?
The Builder Pattern is a creational design pattern that builds complex objects step by step.
It separates object construction from its representation.
Why Use Builder Pattern?
- Handle complex object creation
- Avoid constructors with too many parameters
- Improve readability and maintainability
- Create different representations of same object
Real-Time Scenario
In an Invoice System, an invoice may contain:
- Customer details
- Items
- Tax
- Discount
- Date
👉 Instead of one huge constructor, we build it step by step
Implementation
Step 1: Product (Invoice)
public class Invoice
{
public string Customer { get; set; }
public decimal Amount { get; set; }
public decimal Tax { get; set; }
public decimal Discount { get; set; }
}
Step 2: Builder
public class InvoiceBuilder
{
private readonly Invoice _invoice = new();
public InvoiceBuilder SetCustomer(string customer)
{
_invoice.Customer = customer;
return this;
}
public InvoiceBuilder SetAmount(decimal amount)
{
_invoice.Amount = amount;
return this;
}
public InvoiceBuilder SetTax(decimal tax)
{
_invoice.Tax = tax;
return this;
}
public InvoiceBuilder SetDiscount(decimal discount)
{
_invoice.Discount = discount;
return this;
}
public Invoice Build()
{
return _invoice;
}
}
Usage Example
var invoice = new InvoiceBuilder()
.SetCustomer("Sai")
.SetAmount(1000)
.SetTax(180)
.SetDiscount(50)
.Build();
Key Concept
Instead of:
new Invoice("Sai", 1000, 180, 50); // ❌ confusing
We do:
new InvoiceBuilder()
.SetCustomer("Sai")
.SetAmount(1000)
.Build();
👉 Clear and readable
Advantages
- Improves readability
- Handles complex objects easily
- Flexible object creation
- Avoids constructor overloading
Disadvantages
- More code (builder class)
- Slight complexity increase
- Not needed for simple objects
When to Use
- When object has many properties
- When object creation is complex
- When different configurations are needed
- When readability is important
Real Project Mapping (.NET + Angular)
| Feature | Usage |
|---|---|
| Invoice creation | Builder |
| API request models | Builder |
| Complex DTO creation | Builder |
| Configuration objects | Builder |
Pro Tip (Advanced .NET Usage)
- Combine with Fluent API style (method chaining)
- Use with Immutable objects
- Helpful in test data creation (Test Builders)
Summary
Builder Pattern helps you:
- Build complex objects step by step
- Improve readability and maintainability
- Avoid constructor complexity
👉 Perfect for invoice systems, DTOs, complex object creation
Comments
Post a Comment