public class PizzaA : Pizza { public void DoPizza() { Console.WriteLine("pizza A"); } }
public class PizzaB : Pizza { public void DoPizza() { Console.WriteLine("pizza B"); } } public static class SimplePizzaFacotry { public static Pizza Create(string type) { if (type == "PizzaA") return new PizzaA(); else return new PizzaB(); } }
// Usage public class SimplePizzaFacotryOrder { public void OrderPizza() { Pizza pizza = SimplePizzaFacotry.Create("PizzaA"); pizza.DoPizza(); } }
代码 class PizzaBD { public string Dough { get; set; } public string Sauce { get; set; } public string Topping { get; set; } }
abstract class PizzaBuilder { public PizzaBD pizza { get; protected set; }
public void CreatePizza() { pizza = new PizzaBD(); }
public abstract void BuildDough(); public abstract void BuildSauce(); public abstract void BuildTopping(); }
class HawaiianPizzaBuilder : PizzaBuilder { public override void BuildDough() { pizza.Dough = "Cross"; }
public override void BuildSauce() { pizza.Sauce = "Mild"; }
public override void BuildTopping() { pizza.Topping = "Ham+Pineapple"; } }
class SpicyPizzaBuilder : PizzaBuilder { public override void BuildDough() { pizza.Dough = "Pan Baked"; }
public override void BuildSauce() { pizza.Sauce = "Hot"; }
public override void BuildTopping() { pizza.Topping = "Pepperoni+Salami"; } }
class Cook { public PizzaBuilder PizzaBuilder { get; set; }
public PizzaBD Pizza { get { return PizzaBuilder.pizza; } }
public void MakePizza() { PizzaBuilder.CreatePizza(); PizzaBuilder.BuildDough(); PizzaBuilder.BuildSauce(); PizzaBuilder.BuildTopping(); } }
// usage public class CallBuilder { public void OrderPizza() { Cook cook = new Cook(); cook.PizzaBuilder = new SpicyPizzaBuilder(); cook.MakePizza(); cook.PizzaBuilder = new HawaiianPizzaBuilder(); cook.MakePizza(); } }
5. Facade Pattern 外观模式
提到了Builder模式,也就顺便提一下Facade模式。两者类似处在于都是建立一系列对象,区别在于Builder模式创建一系列有依赖关系的子类,而Facade模式则是建立一个将复杂的子类简化和集中化的通道。还是以Pizza为例,客户吃完付款,需要Waiter收取现金/卡,然后财务做账/transfer之后打印发票,返回。对客户来说后端多的一系列动作他并不关心,PizzaPayFacade提供给客户一个Pay方法,方法里面完成这一系列的动作[可能包括类的实现]。代码稍后提供。大家可以先参考First We try, then we trust的Facade说明的代码示例 http://www.VEVb.com/zhenyulu/articles/55992.html