使用多个简单的对象一步一步构建成一个复杂的对象
将一个复杂的构建与其表示相分离,使得同样的构建过程可以创建不同的表示
示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
| class Product { IList<string> parts = new List<string>(); public void Add(string part) { parts.Add(part); } public void Show() { Console.WriteLine("产品创建--"); parts.Foreach(p => Console.WriteLine(p)); } }
abstract class Builder { public abstract void BuildPartA(); public abstract void BuildPartB(); public abstract Product GetResult(); }
class ConcreateBuilder1 : Builder { private Product product = new Product(); public override void BuildPartA() { product.Add("Part A"); } public override void BuildPartB() { product.Add("Part B"); } public override void GetResult() { return product; } } class ConcreateBuilder2 : Builder { private Product product = new Product(); public override void BuildPartA() { product.Add("Part X"); } public override void BuildPartB() { product.Add("Part Y"); } public override void GetResult() { return product; } }
class Director { public void Construct(Builder builder) { builder.BuildPartA(); builder.BuildPartB(); } }
Director director = new Director(); Builder b1 = new ConcreateBuilder1(); Builder b2 = new ConcreateBuilder2();
director.Construct(b1); Product p1 = b1.GetResult(); p1.Show();
director.Construct(b2); Product p2 = b2.GetResult(); p2.Show();
|
建造者与外观模式对比
建造者的目的是希望用同样的生产过程,根据不同的生产者得到不同的产品。需要重写
外观模式则是将多个对象组合起来,它不需要生产者,也不需要得到不同的结果。不需要重写