建造者模式(Builder Pattern)是一种对象构造模式,它可以将一个复杂对象的构建和它的表示分离,使得同样的构建过程可以创建不同的表示。这种模式是为了将构建复杂对象的过程和部件解耦,提供更好的代码复用性。
正文建造者模式常用于以下场景:
优势:
劣势:
创建一个披萨类
public class pizza
{
//生面团
public string Dough { get; set; }
//酱
public string Sauce { get; set; }
//腊肠
public string Sausage { get; set; }
public string Formula()
{
return this.Dough " " this.Sauce " " this.Sausage;
}
}
抽象建造者
/// <summary>
/// 抽象建造者
/// </summary>
public abstract class PizzaBuilder
{
protected Pizza pizza;
/// <summary>
/// 取得一个披萨
/// </summary>
/// <returns></returns>
public Pizza GetPizza()
{
return pizza;
}
/// <summary>
/// 创建一个新披萨
/// </summary>
public void CreateNewPizza()
{
pizza = new Pizza();
}
public abstract void BuildDough();
public abstract void BuildSauce();
public abstract void BuildSausage();
}
具体建造者
/// <summary>
/// 具体建造者
/// </summary>
public class HawaiianPizzaBuilder : PizzaBuilder
{
public override void BuildDough()
{
pizza.Dough = "Cross";
}
public override void BuildSauce()
{
pizza.Sauce = "Chili";
}
public override void BuildSausage()
{
pizza.Sausage = "HamAndPineapple";
}
}
执行者
public class Cook
{
private PizzaBuilder pizzaBuilder;
public void SetPizzaBuilder(PizzaBuilder pizzaBuilder)
{
this.pizzaBuilder = pizzaBuilder;
}
public Pizza GetPizza()
{
return this.pizzaBuilder.GetPizza();
}
/// <summary>
/// 创建一份披萨
/// </summary>
public void ConstructPizza()
{
this.pizzaBuilder.CreateNewPizza();
this.pizzaBuilder.BuildDough();
this.pizzaBuilder.BuildSauce();
this.pizzaBuilder.BuildSausage();
}
}
事件代码
private void btnCook_Click(object sender, EventArgs e)
{
Cook cook = new Cook();
//创建一个披萨
HawaiianPizzaBuilder hawaiian = new HawaiianPizzaBuilder();
cook.SetPizzaBuilder(hawaiian);
cook.ConstructPizza();
//取得做好的披萨
Pizza pizza = cook.GetPizza();
MessageBox.Show(pizza.Formula());
}
Copyright © 2024 妖气游戏网 www.17u1u.com All Rights Reserved