为了应对复杂对象的创建,其通常由各个部分的子对象用一定的算法构成;由于需求的变化,这个复杂对象的各个部分经常面临着剧烈的变化,但是将它们组合在一起的算法确相对稳定。
using System; using System.Collections; using System.Reflection; namespace DapperTest.Models { // Food类,即产品类 public class Food { Hashtable food = new Hashtable(); // 添加食品 public void Add(string strName, string Price) { food.Add(strName, Price); } // 显示食品清单 public void Show() { IDictionaryEnumerator myEnumerator = food.GetEnumerator(); Console.WriteLine("Food List:"); Console.WriteLine("------------------------------"); string strfoodlist = ""; while (myEnumerator.MoveNext()) { strfoodlist = strfoodlist + "\n\n" + myEnumerator.Key.ToString(); strfoodlist = strfoodlist + ":\t" + myEnumerator.Value.ToString(); } Console.WriteLine(strfoodlist); Console.WriteLine("\n------------------------------"); } } // FoodManager类,即指导者 public class FoodManager { public void Construct(Builder builder) { builder.BuildHamb(); builder.BuildCoke(); builder.BuildChip(); } } // Builder类,即抽象建造者类,构造套餐 public abstract class Builder { // 添加汉堡 public abstract void BuildHamb(); // 添加可乐 public abstract void BuildCoke(); // 添加薯条 public abstract void BuildChip(); // 返回结果 食品对象 public abstract Food GetFood(); } // NormalBuilder类,具体构造者,普通套餐 public class NormalBuilder : Builder { private Food NormalFood = new Food(); public override void BuildHamb() { NormalFood.Add("NormalHamb", "¥10.00"); } public override void BuildCoke() { NormalFood.Add("CokeCole", "¥4.50"); } public override void BuildChip() { NormalFood.Add("FireChips", "¥2.00"); } public override Food GetFood() { return NormalFood; } } // GoldBuilder类,具体构造者,黄金套餐 public class GoldBuilder : Builder { private Food GoldFood = new Food(); public override void BuildHamb() { GoldFood.Add("GoldHamb", "¥25.00"); } public override void BuildCoke() { GoldFood.Add("CokeCole", "¥4.50"); } public override void BuildChip() { GoldFood.Add("FireChips", "¥3.50"); } public override Food GetFood() { return GoldFood; } } //调用 public class BuilderPattern { public static void BuildTest() { FoodManager foodmanager = new FoodManager(); Console.WriteLine("Please Enter Food No:"); string foodType = Console.ReadLine(); if (foodType == "1") { foodType = "NormalBuilder"; } if (foodType == "2") { foodType = "GoldBuilder"; } Builder instance = (Builder)Assembly.Load("DapperTest").CreateInstance("DapperTest.Models." + foodType); foodmanager.Construct(instance); Food food = instance.GetFood(); food.Show(); } } }