📜  c# builder pattern fluent example - C# (1)

📅  最后修改于: 2023-12-03 14:59:39.818000             🧑  作者: Mango

C# Builder Pattern Fluent Example

The Builder Pattern is a creational design pattern used to create objects by providing a flexible and step-by-step approach. It allows the creation of complex objects without exposing the inner workings to the client directly.

Fluent Builder Pattern

The Fluent Builder Pattern is a variation of the Builder Pattern that provides a fluent interface for building objects. It helps to create complex objects in a more readable and easy-to-understand way. This pattern is widely used in C# in various applications.

Problem

Consider a scenario where you have to create an object that has multiple properties, and each property has multiple possible values. It becomes complex to manage the creation of such an object using a regular constructor.

Solution

The solution is to use the Fluent Builder Pattern, which provides a more flexible and easy-to-understand approach. The Fluent Builder Pattern allows you to chain the different properties of an object together using a fluent interface.

Example

Here is an example of how to use the Fluent Builder Pattern in C#:

public class Car
{
    public string Make { get; set; }
    public string Model { get; set; }
    public int Year { get; set; }
    public string Color { get; set; }
}

public class CarBuilder
{
    private Car car;

    public CarBuilder()
    {
        car = new Car();
    }

    public CarBuilder SetMake(string make)
    {
        car.Make = make;
        return this;
    }

    public CarBuilder SetModel(string model)
    {
        car.Model = model;
        return this;
    }

    public CarBuilder SetYear(int year)
    {
        car.Year = year;
        return this;
    }

    public CarBuilder SetColor(string color)
    {
        car.Color = color;
        return this;
    }

    public Car Build()
    {
        return car;
    }
}

In the above code, we have defined a Car class that we want to create using the Fluent Builder Pattern. Then we created a CarBuilder class that provides fluent methods to set the different properties of a Car object.

To create a car object, we can chain the different methods of the CarBuilder class together like this:

var carBuilder = new CarBuilder();
var car = carBuilder.SetMake("Honda").SetModel("Accord").SetYear(2019).SetColor("Grey").Build();

In the above code, we first create a new instance of the CarBuilder class. Then we set the different properties of the car object using the fluent methods of the CarBuilder class. Finally, we call the Build method of the CarBuilder class to get the car object.

Conclusion

The Fluent Builder Pattern is a powerful and flexible technique for creating complex objects in C#. It provides a more readable and easy-to-understand approach to object creation. By using this pattern, you can create objects step by step and get a final object using the Build method.