[review]Design Pattern:Builder

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.

转载于:https://www.cnblogs.com/sanjia/archive/2011/12/05/2277333.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值