- Creational pattern
- Builder Pattern:- The intent of the builder pattern is to separate the construction of complex object from its representation. By doing so the same construction process can create different representations.
- It improves modularity by improving the way the complex object is constructed and represented.
- you have to keep immutability of the object and at the same time and you have to create the object with different set of attributes.
Bike
namespace builder
{
public class Bike
{
private string bikeType;
private readonly List parts = new();
public Bike(string bikeType)
{
this.bikeType = bikeType;
}
public void AddPart(string part)
{
parts.Add(part);
}
public override string ToString()
{
return String.Join(Environment.NewLine,
parts.Select(x => String.Join(", ", x)));
}
}
}
Bike Builder
namespace builder
{
public abstract class BikeBuilder
{
public Bike Bike { get; set; }
public BikeBuilder(string bikeType)
{
Bike = new Bike(bikeType);
}
public abstract void BuildEngine();
}
public class RoyalEnfield : BikeBuilder
{
public RoyalEnfield() : base("Enfield Powerful Engine")
{
}
public override void BuildEngine()
{
Bike.AddPart("Enfiled Engine");
Bike.AddPart("Enfiled Extra Part added");
}
}
public class SplenderBike : BikeBuilder
{
public SplenderBike() : base("Splender Normal engine")
{
}
public override void BuildEngine()
{
Bike.AddPart("Enfiled Engine");
}
}
}
BikeFactory
namespace builder
{
public class BikeFactory
{
private BikeBuilder? _builder;
public void CreateBike(BikeBuilder builder)
{
_builder = builder;
_builder.BuildEngine();
}
public void ShowParts()
{
Console.WriteLine(_builder?.Bike.ToString());
}
}
}
Program.cs
using builder;
var obj = new BikeFactory();
obj.CreateBike(new RoyalEnfield());
obj.ShowParts();
OUTPUT
Enfiled Engine
Enfiled Extra Part added
Github url