C# Builder Design Pattern
Discover how the C# Builder Design Pattern simplifies complex object creation in software development. Learn implementation, benefits, and best practices with code examples.
The Builder Pattern is a creational design pattern that separates the construction of a complex object from its representation. Rather than relying on multiple constructors, it offers a fluent style approach, which enhances readability, flexibility, and error handling.
Key benefits include:
- Avoiding "telescoping constructors" (i.e., too many parameters)
- Ensuring object consistency through validation at each step
- Improving code maintainability, particularly for large projects
- Supporting immutable objects, making them thread-safe by default
Let’s break down the code
Define the Object
public enum CarType
{
Sedan,
Crossover
};
public record Car
{
public CarType Type;
public int WheelSize;
}
Create the Builder
public class CarBuilder
{
public static ISpecifyCarType Create()
{
return new Impl();
}
public interface ISpecifyCarType
{
public ISpecifyWheelSize OfType(CarType type);
}
public interface ISpecifyWheelSize
{
public IBuildCar WithWheels(int size);
}
public interface IBuildCar
{
public Car Build();
}
private class Impl :
ISpecifyCarType,
ISpecifyWheelSize,
IBuildCar
{
private readonly Car car = new();
public ISpecifyWheelSize OfType(CarType type)
{
car.Type = type;
return this;
}
public IBuildCar WithWheels(int size)
{
switch (car.Type)
{
case CarType.Crossover when size < 17 || size > 20:
case CarType.Sedan when size < 15 || size > 17:
throw new
ArgumentException($"Wrong size of wheel for {car.Type}.");
}
car.WheelSize = size;
return this;
}
public Car Build()
{
return car;
}
}
}
Using the Builder
var car = CarBuilder.Create()
.OfType(CarType.Crossover)
.WithWheels(18)
.Build();
Console.WriteLine(car);