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();
}
}