建造者模式(Builder)
1 /* 2 * 建造者模式是一种创建型模式,它主要是应对项目中一些复杂对象的创建工作。 3 * 所谓“复杂对象”,是指此对象中还含有其它的子对象。 4 * 我们现在定义一个场景:汽车生产必须包含车轮(Wheel)、油箱(OilBox)和车身(Body), 5 * 应用建造者模式,用C#控制台应用程序实现该设计,构建BMW品牌和BenZ品牌汽车生产。 6 */ 7 using System; 8 using System.Collections.Generic; 9 using System.Linq; 10 using System.Text; 11 12 namespace Builder 13 { 14 class Car 15 { 16 IList<string> parts = new List<string>(); 17 public void Add(string part) 18 { 19 parts.Add(part); 20 } 21 public void Show() 22 { 23 Console.WriteLine("\n创建产品\nBegin"); 24 foreach (string part in parts) 25 { 26 Console.WriteLine("创建:"+part); 27 } 28 Console.WriteLine("End"); 29 } 30 } 31 abstract class Builder 32 { 33 public abstract void BuildWheel(); 34 public abstract void BuildOilBox(); 35 public abstract void BuildBody(); 36 public abstract Car GetProduct(); 37 } 38 class BMWBuilder : Builder 39 { 40 private Car car = new Car(); 41 public override void BuildWheel() 42 { 43 car.Add("BMW-Wheel"); 44 } 45 public override void BuildOilBox() 46 { 47 car.Add("BMW-OilBox"); 48 } 49 public override void BuildBody() 50 { 51 car.Add("BMW-Body"); 52 } 53 public override Car GetProduct() 54 { 55 return car; 56 } 57 58 } 59 class BenZBuilder : Builder 60 { 61 private Car car = new Car(); 62 public override void BuildWheel() 63 { 64 car.Add("BenZ-Wheel"); 65 } 66 public override void BuildOilBox() 67 { 68 car.Add("BenZ-OilBox"); 69 } 70 public override void BuildBody() 71 { 72 car.Add("BenZ-Body"); 73 } 74 public override Car GetProduct() 75 { 76 return car; 77 } 78 79 } 80 class Director 81 { 82 public void Construct(Builder bd) 83 { 84 bd.BuildWheel(); 85 bd.BuildOilBox(); 86 bd.BuildBody(); 87 } 88 } 89 class Program 90 { 91 static void Main(string[] args) 92 { 93 Director dt = new Director(); 94 Builder bmw = new BMWBuilder(); 95 Builder benz = new BenZBuilder(); 96 97 dt.Construct(bmw); 98 Car car1 = bmw.GetProduct(); 99 car1.Show(); 100 101 dt.Construct(benz); 102 Car car2 = benz.GetProduct(); 103 car2.Show(); 104 } 105 } 106 }
![字节跳动内推](https://img2020.cnblogs.com/blog/323808/202004/323808-20200415172728571-1992447742.jpg)
找我内推: 字节跳动各种岗位
作者:
ZH奶酪(张贺)
邮箱:
cheesezh@qq.com
出处:
http://www.cnblogs.com/CheeseZH/
*
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。