C# builder pattern

C# builder pattern sample


class Program
{
static void Main(string[] args)
{
string[] partlist1 = { "a", "b", "c" };
string[] partlist2 = { "1", "2", "3" };

Builder builder = new ConcreateClass1();
Director.Construct(builder, partlist1);
Product product1 = builder.GetProduct();
Console.WriteLine(product1.ToString());

builder = new ConcreateClass2();
Director.Construct(builder, partlist2);
Product product2 = builder.GetProduct();
Console.WriteLine(product2.ToString());

Console.ReadLine();
}
}

class Director
{
public static void Construct(Builder builder, string[] parts)
{
parts.ToList().ForEach(z => {
builder.BuildPart(z);
});
}
}

public abstract class Builder
{
public abstract void BuildPart(string partName);
public abstract Product GetProduct();
}

public class ConcreateClass1 : Builder
{

private Product part = new Product();

public override void BuildPart(string partName)
{
part.Add(partName);
}

public override Product GetProduct()
{
return part;
}
}

public class ConcreateClass2 : Builder
{

private Product part = new Product();

public override void BuildPart(string partName)
{
part.Add(partName);
}

public override Product GetProduct()
{
return part;
}
}

public class Product
{
private List<string> _parts = new List<string>();

public void Add(string part)
{
this._parts.Add(part);
}

public override string ToString()
{
string parts = string.Empty;
_parts.ForEach(z =>
{
parts += " " + z;
});

return String.Format("Part list {0}", parts);
}
}

Advertisements

#builder-pattern, #csharp-pattern