结构

生成器模式

说明

Separate the construction of a complex object from its representation allowing the same construction process to create various representations.

将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。

适用条件

  • 当创建复杂对象的算法应该独立于该对象的组成部分以及它们的装配方式时;
  • 当构造过程必须允许被构造的对象有不同的表示时。

实现

abstract class PizzaBuilder {

   protected Pizza Pizza;

   public Pizza GetPizza() {
      return this.Pizza;
   }

   public void CreateNewPizzaProduct() {
      this.Pizza = new Pizza();
   }

   public abstract void BuildDough();

   public abstract void BuildSauce();

   public abstract void BuildTopping();

}

class HawaiianPizzaBuilder : PizzaBuilder {

   public override void BuildDough() {
      this.Pizza.Dough = "cross";
   }

   public override void BuildSauce() {
      this.Pizza.Sauce = "mild";
   }

   public override void BuildTopping() {
      this.Pizza.Topping = "ham+pineapple";
   }
}

class SpicyPizzaBuilder : PizzaBuilder {

   public override void BuildDough() {
      this.Pizza.Dough = "pan baked";
   }

   public override void BuildSauce() {
      this.Pizza.Sauce = "hot";
   }

   public override void BuildTopping() {
      this.Pizza.Topping = "pepperoni + salami";
   }
}

class Cook {

   private PizzaBuilder _pizzaBuilder;

   public void SetPizzaBuilder(PizzaBuilder pb) {
      _pizzaBuilder = pb;
   }

   public Pizza GetPizza() {
      return _pizzaBuilder.GetPizza();
   }

   public void ConstructPizza() {
      _pizzaBuilder.CreateNewPizzaProduct();
      _pizzaBuilder.BuildDough();
      _pizzaBuilder.BuildSauce();
      _pizzaBuilder.BuildTopping();
   }
}

public class Pizza {

   private string _dough = string.Empty;
   private string _sauce = string.Empty;
   private string _topping = string.Empty;

   public string Dough {
      get {
         return _dough;
      }
      set {
         _dough = value;
      }
   }

   public string Sauce {
      get {
         return _sauce;
      }
      set {
         _sauce = value;
      }
   }

   public string Topping {
      get {
         return _topping;
      }
      set {
         _topping = value;
      }
   }
}

class Program {

   static void Main(string[] args) {
      PizzaBuilder hawaiianPizzaBuilder = new HawaiianPizzaBuilder();
      var cook = new Cook();
      cook.SetPizzaBuilder(hawaiianPizzaBuilder);
      cook.ConstructPizza();
      // create the product
      var hawaiian = cook.GetPizza();

      PizzaBuilder spicyPizzaBuilder = new SpicyPizzaBuilder();
      cook.SetPizzaBuilder(spicyPizzaBuilder);
      cook.ConstructPizza();
      // create another product
      var spicy = cook.GetPizza();
   }

}