将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
创建复杂对象的算法应该独立于该对象的组成部分以及它们的装配方式时适用
//定义一个产品类
class Product
{
//组成部分的集合
IList<string> parts = new List<string>();
public void Add(string part)
{
parts.Add(part);
}
public void Show()
{
Console.WriteLine("产品组成---");
foreach (string part in parts)
{
Console.WriteLine(part);
}
}
}
//抽象一个建造者
abstract class Builder
{
public abstract void BuildPartA();
public abstract void BuildPartB();
public abstract Product GetResult();
}
//建造者具体实现类
class ConcreteBuilder1 : Builder
{
Product pro = new Product();
public override void BuildPartA()
{
pro.Add("partA");
}
public override void BuildPartB()
{
pro.Add("partB");
}
public override Product GetResult()
{
return pro;
}
}
class ConcreteBuilder2 : Builder
{
Product pro = new Product();
public override void BuildPartA()
{
pro.Add("partX");
}
public override void BuildPartB()
{
pro.Add("partY");
}
public void BuildPartC()
{
pro.Add("partZ");
}
public override Product GetResult()
{
return pro;
}
}
//创建指挥者
class Director
{
public void Construct(Builder builder)
{
builder.BuilderPartA();
builder.BuilderPartB();
}
}
调用:
Director dir = new Director();
Builder bu1 = new ConcreteBuilder1();
ConcreteBuilder2 bu2 = new ConcreteBuilder2();
dir.Construct(bu1);
bu1.GetResult().Show();
dir.Construct(bu2);
bu2.BuildPartC();
bu2.GetResult().Show();