工厂模式但对象参数 [英] Factory Pattern but with object Parameters

查看:291
本文介绍了工厂模式但对象参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看看下面的经典工厂模式:

Take the following classic factory pattern:

public interface IPizza
{
    decimal Price { get; }
}

public class HamAndMushroomPizza : IPizza
{
    decimal IPizza.Price
    {
        get
        {
            return 8.5m;
        }
    }
}
public abstract class PizzaFactory
{
    public abstract IPizza CreatePizza(ItalianPizzaFactory.PizzaType pizzaType);
}

public class ItalianPizzaFactory : PizzaFactory
{
    public enum PizzaType
    {
        HamMushroom,
        Deluxe,
        Hawaiian
    }

    public override IPizza CreatePizza(PizzaType pizzaType)
    {
        switch (pizzaType)
        {
            case PizzaType.HamMushroom:
                return new HamAndMushroomPizza();
            case PizzaType.Hawaiian:
                return new HawaiianPizza();
            default:
                throw new ArgumentException("The pizza type " + pizzaType + " is not recognized.");
        }
    }
}

如果一个(或多个)混凝土比萨饼的具体要求在建设的具体实施的参数。例如,可以说在HamAndMushroom工厂需要一个所谓的参数,MushroomType此参数将需要实例化对象?

What if one (or many) of the Concrete Pizzas requires a parameter specific to the concrete implementation at construction. For example, lets say the HamAndMushroom factory requires a parameter called, MushroomType and this parameter would be required to instantiate the object?

推荐答案

您可以将参数添加到您的工厂的创建者方法(S)。但是,如果参数的数量也越来越高(对我来说这将是超过2-3),特别是如果某些或所有这些参数都是可选的合理的默认值,可以考虑将工厂变成的构建器来代替。

You can add parameters to the creator method(s) of your factory. However, if the number of parameters is getting higher (for me that would be more than 2-3), and especially if some or all of those parameters are optional with reasonable default values, you may consider turning the factory into a Builder instead.

这可能尤其适合于比萨,在那里你平时有浇头的地壳一样,只是用不同的(组合)。建设者车型非常接近例如订购的常见方式与香肠,番茄,玉米和双奶酪比萨。 OTOH为预定义的比萨饼,你可能需要定义帮手工厂方法,例如 createMargaritaPizza createHawaiiPizza ,然后在内部使用生成器来创建一个比萨饼特定于该种比萨饼的浇头。

That may be especially appropriate for pizzas, where you usually have the same crust, just with different (combinations) of toppings. A Builder models very closely the common way of ordering e.g. "a pizza with salami, tomatoes, maize and double cheese". OTOH for "predefined" pizzas you may want to define helper factory methods, e.g. createMargaritaPizza or createHawaiiPizza which then internally use the builder to create a pizza with the toppings specific to that kind of pizza.

这篇关于工厂模式但对象参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆