Middle
Provide an example of implementing the 'Builder' design pattern in C#.
sobes.tech AI
Answer from AI
The "Builder" pattern separates the process of constructing a complex object from its representation so that the same construction process can create different representations. It is used when creating an object requires multiple steps and configurations.
// Abstract builder declares an interface for creating parts of the object.
public abstract class Builder
{
public abstract void BuildPartA();
public abstract void BuildPartB();
public abstract Product GetResult();
}
// Concrete builder implements the Builder interface
// and constructs and assembles parts of the product.
public class ConcreteBuilder : Builder
{
private Product _product = new Product();
public override void BuildPartA()
{
_product.Add("PartA");
}
public override void BuildPartB()
{
_product.Add("PartB");
}
public override Product GetResult()
{
return _product;
}
}
// Product represents a complex object that needs to be built.
public class Product
{
private List<string> _parts = new List<string>();
public void Add(string part)
{
_parts.Add(part);
}
public void ListParts()
{
Console.WriteLine("Product parts: " + string.Join(", ", _parts));
}
}
// Director constructs the object using the Builder interface.
public class Director
{
public void Construct(Builder builder)
{
builder.BuildPartA();
builder.BuildPartB();
}
}
// Usage example
public class Program
{
public static void Main(string[] args)
{
Director director = new Director();
ConcreteBuilder builder = new ConcreteBuilder(); // Create a specific builder
director.Construct(builder); // Director guides the construction process
Product result = builder.GetResult(); // Get the finished product
result.ListParts(); // Output the parts of the product
}
}
Main components:
- Builder: Abstract interface for creating parts of the final product.
- ConcreteBuilder: Concrete implementation of Builder that constructs and assembles parts of the product.
- Director: Class that uses Builder for step-by-step construction of the object without knowing its specific type.
- Product: The complex object being built.
This example demonstrates how Director uses ConcreteBuilder to create a Product step by step, separating the construction process from its representation.