意图:
将一个复杂对象的构建与其表示相分离,使得同样的构建过程可以创建不同的表示。
public class Car{
private IList<string> parts = new List<string>();
public void Add(string part){
parts.Add(part);
}
public void Show(){
foreach(var part in parts){
Console.WriteLine("组装"+ part);
}
}
}
public abstract class Builder{
public abstract void BuildCarDoor();
public abstract void BuildCarWheel();
public abstract Car GetCar();
}
public class BMWBuilder:Builder{
var car = new Car();
public override void BuilderCarDoor(){
car.Add("add a Door");
}
public override void BuilderCarWheel(){
car.Add("add a Wheel");
}
public override Car GetCar(){
return car;
}
}
public class BYDBuilder:Builder{
var car = new Car();
public override void BuilderCarDoor(){
car.Add("add a Door");
}
public override void BuilderCarWheel(){
car.Add("add a Wheel");
}
public override Car GetCar(){
return car;
}
}
public class Director{
public void Construct(Builder builder){
builder.BuilderCarDoor();
builder.BuilderCarWheel();
}
}
public class Client(){
static void Main(){
var director = new Director();
var bmwBuilder = new BMWBuilder();
var bydBuilder = new BYDBuilder();
director.Construct(bmwBuilder);
var bmwCar = bmwBuilder.GetCar();
bmwCar.Show();
director.Construct(bydBuilder);
var bydCar = bydBuilder.GetCar();
bydCar.Show();
}
}
优点:客户端不必知道产品内部组成的细节。
具体的建造者类之间是相互独立的,容易扩展。
缺点:产生了多余的Build对象和Dirextor类。