How to use Builder Pattern in C#

By FoxLearn 2/16/2024 3:36:50 PM   297
This post shows you How to use Builder Pattern in C#

The Builder Pattern divides the structure of a complex object from its small details, so a similar logic can create objects with different details.

Regular usage: Normal

UML Diagram

Builder Pattern in C#

Classes and objects that participate in this pattern include:

  • Builder: Specifies an abstract interface by creating a part of the Product object.
  • ConcreteBuilder: structure and pair parts of one product by implementing the Builder interface. redefine and record the details it creates. Provide an interface that can return the product details created.
  • Director: create the object using the Builder interface
  • Product: is a complex object created. ConcreteBuilder builds internal product details and defines pairing handling, including classes that define details, and interfaces to concatenate parts that produce the final result.

Implement c# code

public static void Main()
{
    Director director = new Director();

    Builder b1 = new ConcreteBuilder1();
    Builder b2 = new ConcreteBuilder2();

    director.Construct(b1);
    Product p1 = b1.GetResult();
    p1.Show();

    director.Construct(b2);
    Product p2 = b2.GetResult();
    p2.Show();
}

class Director
{
    public void Construct(Builder builder)
    {
        builder.BuildPartA();
        builder.BuildPartB();
    }
}

abstract class Builder
{
    public abstract void BuildPartA();
    public abstract void BuildPartB();
    public abstract Product GetResult();
}

class ConcreteBuilder1 : 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;
    }
}

class ConcreteBuilder2 : Builder

{
    private Product _product = new Product();

    public override void BuildPartA()
    {
        _product.Add("PartX");
    }

    public override void BuildPartB()
    {
        _product.Add("PartY");
    }

    public override Product GetResult()
    {
        return _product;
    }
}

class Product
{
    private List<string> _parts = new List<string>();
    public void Add(string part)
      _parts.Add(part);

    public void Show()
    {
        Console.WriteLine("\nProduct Parts -------");
        foreach (string part in _parts)
            Console.WriteLine(part);
    }
}