Builder
Decouple the appearance from the construct process(algorithm) for a complicated object, the algorithm can be used for so much appearance. for reusing the algorithm, for hiding the details from the client. The appearance can be showed without leaving any parts needed with the help of the unified interface provided by the Director.
When we use this pattern
as i told above.
Roles in this pattern
- Builder: define the interface for creating the part of the product
- ConcreteBuilder: implement the Builder interface for the very certain product, for the very given appearance. and also provide an interface for retrieve the current product that the current ConcreteBuilder is trying to build
- Director:define the interface to create the product by the interface provided by the Builder, the interface design the algorithm about how the product is created and how to use the part of the interface implemented by the ConcreteBuilder, the order how the parts show themself
- Product: the one we want to create.
Demo
namespace Builder
{
public class Product
{
List<string> parts = new List<string>();
public void Add(string part)
{
parts.Add(part);
}
public void ShowProduct()
{
foreach (string part in parts)
{
Console.WriteLine(part);
}
}
}
public abstract class Builder
{
public abstract void BuilderA();
public abstract void BuilderB();
public abstract Product GetResult();
}
public class ConcreteBuilder1 : Builder
{
private Product product = new Product();
public override void BuilderA()
{
product.Add("1A");
}
public override void BuilderB()
{
product.Add("1B");
}
public override Product GetResult()
{
return product;
}
}
public class ConcreteBuilder2 : Builder
{
private Product product = new Product();
public override void BuilderA()
{
product.Add("2A");
}
public override void BuilderB()
{
product.Add("2B");
}
public override Product GetResult()
{
return product;
}
}
public class Director
{
public void Construct(Builder builder)
{
builder.BuilderA();
builder.BuilderB();
}
}
public class Client
{
static void Main(string[] args)
{
Director director = new Director();
Builder b1 = new ConcreteBuilder1();
Builder b2 = new ConcreteBuilder2();
director.Construct(b1);
Product p1 = b1.GetResult();
p1.ShowProduct();
director.Construct(b2);
Product p2 = b2.GetResult();
p2.ShowProduct();
Console.Read();
}
}
}
IMO, this pattern can be learnt with the Factory, the Template and the Strategy... They are some kind similar to each other. BUT they are different, it is interesting to differentiate them. and it is also useful to have a better comprehension and understanding for all the pattern and OOP if you dig them together.