using System;
namespace BuilderDesignPatternExample
{
// 产品类
public class Product
{
public string PartA { get; set; }
public string PartB { get; set; }
public string PartC { get; set; }
}
// 建造者抽象类
public abstract class Builder
{
public abstract void BuildPartA();
public abstract void BuildPartB();
public abstract void BuildPartC();
public abstract Product GetResult();
}
// 具体建造者类
public class ConcreteBuilder : Builder
{
private Product product = new Product();
public override void BuildPartA()
{
product.PartA = "构建部分A";
}
public override void BuildPartB()
{
product.PartB = "构建部分B";
}
public override void BuildPartC()
{
product.PartC = "构建部分C";
}
public override Product GetResult()
{
return product;
}
}
// 指挥者类
public class Director
{
public void Construct(Builder builder)
{
builder.BuildPartA();
builder.BuildPartB();
builder.BuildPartC();
}
}
class Program
{
static void Main(string[] args)
{
Director director = new Director();
Builder builder = new ConcreteBuilder();
director.Construct(builder);
Product product = builder.GetResult();
Console.WriteLine(product.PartA);
Console.WriteLine(product.PartB);
Console.WriteLine(product.PartC);
// 输出产品的各个部分
}
}
}
这段代码展示了如何在C#中实现建造者设计模式。它定义了一个产品类Product
,一个抽象的建造者类Builder
,一个具体的建造者类ConcreteBuilder
,以及一个指挥者类Director
。Director
类负责安排构建过程,而ConcreteBuilder
类则实际构建产品的各个部分。最后,在Main
方法中,我们创建了指挥者、建造者和产品对象,并构建了产品,然后输出了产品的各个部分。