技术开发 频道

创建型模式篇-建造者模式(Builder Pattern)



3.建造者处理指导者的要求,并将部件添加到产品中。餐馆员工(建造者)按照收银员要求的把对应的汉堡,可乐,薯条放入盘子中。这部分是建造者模式里面富于变化的部分,因为顾客选择的套餐不同,套餐的组装过程也不同,这步完成产品对象的创建工作。

程序实现:
1using System; 2 3namespace KFC 4{ 5 /**//// <summary> 6 /// Builder类,即抽象建造者类,构造套餐 7 /// </summary> 8 public abstract class Builder 9 { 10 /**//// <summary> 11 /// 添加汉堡 12 /// </summary> 13 public abstract void BuildHamb(); 14 15 /**//// <summary> 16 /// 添加可乐 17 /// </summary> 18 public abstract void BuildCoke(); 19 20 /**//// <summary> 21 /// 添加薯条 22 /// </summary> 23 public abstract void BuildChip(); 24 25 /**//// <summary> 26 /// 返回结果 27 /// </summary> 28 /// <returns>食品对象</returns> 29 public abstract Food GetFood(); 30 } 31} 32
1using System; 2 3namespace KFC 4{ 5 /**//// <summary> 6 /// NormalBuilder类,具体构造者,普通套餐 7 /// </summary> 8 public class NormalBuilder:Builder 9 { 10 private Food NormalFood = new Food(); 11 12 public override void BuildHamb() 13 { 14 NormalFood.Add("NormalHamb","¥10.50"); 15 } 16 17 public override void BuildCoke() 18 { 19 NormalFood.Add("CokeCole","¥4.50"); 20 } 21 22 public override void BuildChip() 23 { 24 NormalFood.Add("FireChips","¥2.00"); 25 } 26 27 public override Food GetFood() 28 { 29 return NormalFood; 30 } 31 32 } 33} 34
1using System; 2 3namespace KFC 4{ 5 /**//// <summary> 6 /// GoldBuilder类,具体构造者,黄金套餐 7 /// </summary> 8 public class GoldBuilder:Builder 9 { 10 private Food GoldFood = new Food(); 11 12 public override void BuildHamb() 13 { 14 GoldFood.Add("GoldHamb","¥13.50"); 15 } 16 17 public override void BuildCoke() 18 { 19 GoldFood.Add("CokeCole","¥4.50"); 20 } 21 22 public override void BuildChip() 23 { 24 GoldFood.Add("FireChips","¥3.50"); 25 } 26 27 public override Food GetFood() 28 { 29 return GoldFood; 30 } 31 32 } 33} 34


0
相关文章