/// <summary> /// 建造者模式:的基类。 /// 它要求建造过程必须是稳定的。这是与装饰模式的区别 /// </summary> abstract class Builder { public abstract void BuilderPartA(); public abstract void BuilderPartB(); public abstract Product GetResult(); } /// <summary> /// 具体的建造者 /// </summary> class ConcreteBuilder : Builder { private Product p = new Product(); public override void BuilderPartA() { p.Add("part A"); } public override void BuilderPartB() { p.Add("part B"); } public override Product GetResult() { return p; } } /// <summary> /// 具体建造者2,它亦有它自己固定的构造过程 /// </summary> class ConcreteBuilder2 : Builder { private Product product = new Product(); public override void BuilderPartA() { product.Add("part x"); } public override void BuilderPartB() { product.Add("part Y"); } public override Product GetResult() { return product; } } /// <summary> /// 指挥者类,它指示具体调用那个建造者 /// </summary> class Director { /// <summary> /// 构造产品的具体步骤 /// </summary> public void Constructor(Builder buider) { buider.BuilderPartA(); buider.BuilderPartB(); } } /// <summary> /// 需要构建的对象类 /// </summary> class Product { List<string> parts = new List<string>(); public void Add(string partName) { parts.Add(partName); } public void Show() { foreach (var item in parts) { Console.WriteLine(item); } } } class TestBuilder { public void Run() { ConcreteBuilder buider1 = new ConcreteBuilder(); Director director = new Director(); director.Constructor(buider1); Product p = buider1.GetResult(); p.Show(); ConcreteBuilder2 buider2 = new ConcreteBuilder2(); director.Constructor(buider2); Product p2 = buider2.GetResult(); p2.Show(); } }
建造者模式
来源:https://www.cnblogs.com/363546828/p/3282208.html