概述
在软件系统中,有时候面临着“一个复杂对象”的创建工作,其通常由各个部分的子对象用一定的算法构成;由于需求的变化,这个复杂对象的各个部分经常面临着剧烈的变化,但是将它们组合在一起的算法确相对稳定。如何应对这种变化?如何提供一种“封装机制”来隔离出“复杂对象的各个部分”的变化,从而保持系统中的“稳定构建算法”不随着需求改变而改变?这就是要说的建造者模式。
意图
将一个复杂的构建与其表示相分离,使得同样的构建过程可以创建不同的表示。
Food class
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; namespace BuilderPatternDemo { class Food { Hashtable foodList = new Hashtable(); public void add(string name, double price) { foodList.Add(name, price); } public void show() { IDictionaryEnumerator enumerator = foodList.GetEnumerator(); Console.WriteLine(" Food List"); Console.WriteLine("-----------------------------------------"); string strfoodlist = ""; while (enumerator.MoveNext()) { strfoodlist = strfoodlist + "\n\n" + enumerator.Key.ToString(); strfoodlist = strfoodlist + ":\t" + enumerator.Value.ToString(); } Console.WriteLine(strfoodlist); Console.WriteLine("\n---------------------------------------"); } } }
生产者
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BuilderPatternDemo { interface IBuilder { void productCoke(); void productHumburger(); void productChips(); Food getFood(); } //普通套餐生产者 class CommonBuilder :IBuilder { private Food NormalFood = new Food(); public void productCoke() { NormalFood.add("NormalCoke", 5.0); } public void productHumburger() { NormalFood.add("NormalHumburger", 10.0); } public void productChips() { NormalFood.add("NormalChips", 2.5); } public Food getFood() { return NormalFood; } } //黄金套餐生产者 class GoldBuilder : IBuilder { private Food GoldFood = new Food(); public void productCoke() { GoldFood.add("GoldCoke",10.0); } public void productHumburger() { GoldFood.add("GoldHumburger", 15.0); } public void productChips() { GoldFood.add("GoldChips",8.0); } public Food getFood() { return GoldFood; } } }
服务员
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BuilderPatternDemo { class Director { //服务员 public Food Construct(IBuilder builder) { //生产 builder.productCoke(); builder.productHumburger(); builder.productChips(); //返回生产后的食物 return builder.getFood(); } } }
主函数
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; namespace BuilderPatternDemo { class Program { static void Main(string[] args) { //可以写入配置文件<app setting name=1,value=GoldBuilder> //创建服务员 Director urSister = new Director(); string FoodName = "BuilderPatternDemo.GoldBuilder"; //调用反射机制 IBuilder instance; Type typeGetType = Type.GetType(FoodName); if (FoodName != "") instance = (IBuilder)Activator.CreateInstance(typeGetType); else instance = null; Food myfood = urSister.Construct(instance); myfood.show(); Console.Read(); } } }
|--Food
|--Director Construct(IBuilder builder)传入建造者,返回食物
|--IBuilder productCoke();productHumburger();productChips() Food getFood();
|---CommonBuilder
|---GoldBuilder