建造者模式(Builder):将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
namespace Builder { public 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); } } } public abstract class Builder { public abstract void BuildPartA(); public abstract void BuildPartB(); public abstract Product GetResult(); } public class ConcreteBuilder1 : Builder { private Product product = new Product(); public override void BuildPartA() { product.Add("部件A"); } public override void BuildPartB() { product.Add("部件B"); } public override Product GetResult() { return product; } } public class ConcreteBuilder2 : Builder { private Product product = new Product(); public override void BuildPartA() { product.Add("部件X"); } public override void BuildPartB() { product.Add("部件Y"); } public override Product GetResult() { return product; } } public class Director { public void Construct(Builder builder) { builder.BuildPartA(); builder.BuildPartB(); } } }
测试代码:
Builder.Director director = new Builder.Director(); Builder.Builder b1 = new Builder.ConcreteBuilder1(); Builder.Builder b2 = new Builder.ConcreteBuilder2(); director.Construct(b1); Builder.Product p1 = b1.GetResult(); p1.Show(); director.Construct(b2); Builder.Product p2 = b2.GetResult(); p2.Show();