gpt4 book ai didi

decorator - 通过实际示例了解 "Decorator Pattern"

转载 作者:行者123 更新时间:2023-12-03 04:18:20 26 4
gpt4 key购买 nike

我正在研究装饰器模式,如 GOF 中所述.

请帮助我理解装饰器模式。有人可以举一个用例来说明这在现实世界中有用吗?

最佳答案

Decorator pattern achieves a single objective of dynamically addingresponsibilities to any object.

考虑一个披萨店的例子。在披萨店里,他们会出售几种披萨品种,并且还会在菜单中提供配料。现在想象一下这样一种情况,如果披萨店必须提供披萨和配料的每种组合的价格。即使有四种基本的披萨和 8 种不同的配料,应用程序也会疯狂地维护所有这些披萨和配料的具体组合。

这里是装饰器模式。

根据装饰器模式,您将实现配料作为装饰器,而披萨将由这些配料的装饰器装饰。实际上,每个顾客都会想要他想要的配料,最终的账单金额将由基础披萨和额外订购的配料组成。每个配料装饰师都会知道其正在装饰的比萨饼及其价格。 Topping 对象的 GetPrice() 方法将返回披萨和配料的累计价格。

编辑

这是上面解释的代码示例。

public abstract class BasePizza
{
protected double myPrice;

public virtual double GetPrice()
{
return this.myPrice;
}
}

public abstract class ToppingsDecorator : BasePizza
{
protected BasePizza pizza;
public ToppingsDecorator(BasePizza pizzaToDecorate)
{
this.pizza = pizzaToDecorate;
}

public override double GetPrice()
{
return (this.pizza.GetPrice() + this.myPrice);
}
}

class Program
{
[STAThread]
static void Main()
{
//Client-code
Margherita pizza = new Margherita();
Console.WriteLine("Plain Margherita: " + pizza.GetPrice().ToString());

ExtraCheeseTopping moreCheese = new ExtraCheeseTopping(pizza);
ExtraCheeseTopping someMoreCheese = new ExtraCheeseTopping(moreCheese);
Console.WriteLine("Plain Margherita with double extra cheese: " + someMoreCheese.GetPrice().ToString());

MushroomTopping moreMushroom = new MushroomTopping(someMoreCheese);
Console.WriteLine("Plain Margherita with double extra cheese with mushroom: " + moreMushroom.GetPrice().ToString());

JalapenoTopping moreJalapeno = new JalapenoTopping(moreMushroom);
Console.WriteLine("Plain Margherita with double extra cheese with mushroom with Jalapeno: " + moreJalapeno.GetPrice().ToString());

Console.ReadLine();
}
}

public class Margherita : BasePizza
{
public Margherita()
{
this.myPrice = 6.99;
}
}

public class Gourmet : BasePizza
{
public Gourmet()
{
this.myPrice = 7.49;
}
}

public class ExtraCheeseTopping : ToppingsDecorator
{
public ExtraCheeseTopping(BasePizza pizzaToDecorate)
: base(pizzaToDecorate)
{
this.myPrice = 0.99;
}
}

public class MushroomTopping : ToppingsDecorator
{
public MushroomTopping(BasePizza pizzaToDecorate)
: base(pizzaToDecorate)
{
this.myPrice = 1.49;
}
}

public class JalapenoTopping : ToppingsDecorator
{
public JalapenoTopping(BasePizza pizzaToDecorate)
: base(pizzaToDecorate)
{
this.myPrice = 1.49;
}
}

关于decorator - 通过实际示例了解 "Decorator Pattern",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2707401/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com