一定义: 将一个复杂的构建与其表示相分离相分离,使得同样的构建过程可以创建不同的表示。
二UML类图:
三模试角色与结构:
Product:具体产品
Builder:用来创建Product的抽象接口
ConcreteBuilder:具体的产品建造者,从Builder继承
Director:指挥者,用来根据用户的需求,构建对象
四程序举例
使用生成器模式,建造小机车,假设小车部件可分为“车身款式”“轮子”“发动机”“变速箱”“车身颜色”5个部分,请用生成器模式来生成多款汽车(小汽车,货车,面包车)。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace Builder
{
public class Product
{
ArrayList al = new ArrayList();
public void SetProducts(String parts)
{
al.Add(parts);
}
public void GetProducts()
{
foreach (object o in al)
{
Console.WriteLine(o.ToString());
}
}
}
public abstract class Builder
{
public abstract void BuildType();
public abstract void BuildWheel();
public abstract void BuildEngine();
public abstract void BuildSpeedBox();
public abstract void BulidColor();
public abstract Product GetResult();
}
public class Car : Builder
{
Product p = new Product();
public override void BuildType()
{
p.SetProducts("加长");
}
public override void BuildWheel()
{
p.SetProducts("扁平宽胎");
}
public override void BuildEngine()
{
p.SetProducts("v6");
}
public override void BuildSpeedBox()
{
p.SetProducts("Auto8");
}
public override void BulidColor()
{
p.SetProducts("Red");
}
public override Product GetResult()
{
return p;
}
}
public class Truck : Builder
{
Product p = new Product();
public override void BuildType()
{
p.SetProducts("重卡");
}
public override void BuildWheel()
{
p.SetProducts("很多轮");
}
public override void BuildEngine()
{
p.SetProducts("vvv8");
}
public override void BuildSpeedBox()
{
p.SetProducts("Auto100");
}
public override void BulidColor()
{
p.SetProducts("Black");
}
public override Product GetResult()
{
return p;
}
}
public class Director
{
public void Create(Builder builder)
{
builder.BuildType();
builder.BuildEngine();
builder.BuildSpeedBox();
builder.BuildWheel();
builder.BulidColor();
}
}
class Client
{
static void Main(string[] args)
{
Director d = new Director();
Car c = new Car();
d.Create(c);
Truck t = new Truck();
d.Create(t);
c.GetResult().GetProducts();
t.GetResult().GetProducts();
}
}
}
结果是: