建造者(Builder)模式,将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示
如果使用建造者模式,那么用户就只需要建造的类型就可以得到它们,而具体建造的过程和细节就不需知道了
class Program
{
static void Main(string[] args)
{
Director director = new Director();
Builder builder1 = new ConcreteBuilder1();
Builder builder2 = new ConcreteBuilder2();
director.Construct(builder1);
Product p1 = builder1.GetProduct();
p1.Show();
director.Construct(builder2);
Product p2 = builder2.GetProduct();
p2.Show();
Console.ReadLine();
}
}
//产品类
class Product
{
IList<string> parts = new List<string>();
public void Add(string part)
{
parts.Add(part);
}
public void Show()
{
Console.WriteLine("\n产品 创建----");
foreach (string part in parts)
{
Console.WriteLine(part);
}
}
}
abstract class Builder
{
public abstract void BuilderPartA();
public abstract void BuilderPartB();
public abstract void BuilderPartC();
public abstract Product GetProduct();
}
//具体建造者类
class ConcreteBuilder1 : Builder
{
private Product product = new Product();
public override void BuilderPartA()
{
product.Add("部件A");
}
public override void BuilderPartB()
{
product.Add("部件B");
}
public override void BuilderPartC()
{
product.Add("部件C");
}
public override Product GetProduct()
{
return product;
}
}
class ConcreteBuilder2 : Builder
{
private Product product = new Product();
public override void BuilderPartA()
{
product.Add("部件X");
}
public override void BuilderPartB()
{
product.Add("部件Y");
}
public override void BuilderPartC()
{
product.Add("部件Z");
}
public override Product GetProduct()
{
return product;
}
}
class Director
{
public void Construct(Builder builder)
{
builder.BuilderPartA();
builder.BuilderPartB();
builder.BuilderPartC();
}
}
建造者模式是在当创建复杂对象的算法应该独立于该对象的组成部分以及它们的装配方式时适用的模式