定义:将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
适用场景:建造者模式是在当创建复杂对象的算法,应该独立于该对象的组成部分以及它们的装配方式时适用的模式。
示例代码:
/// <summary>
/// 建造者
/// </summary>
abstract class Builder
{
public abstract void BuilderPartA();
public abstract void BuilderPartB();
public abstract Product GetResult();
}
class ConcreteBuilder1 : Builder
{
private Product product = new Product();
public override void BuilderPartA()
{
product.Add("部件A");
}
public override void BuilderPartB()
{
product.Add("部件B");
}
public override Product GetResult()
{
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 Product GetResult()
{
return product;
}
}
class Director
{
public void Construct(Builder builder)
{
builder.BuilderPartA();
builder.BuilderPartB();
}
}
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);
}
}
}
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.Show();
director.Construct(b2);
Product p2 = b2.GetResult();
p2.Show();
Console.Read();
}
标签:Product,C#,void,建造,product,模式,Add,override,public From: https://www.cnblogs.com/KevinSteven/p/17179527.html