Factory Pattern but with object Parameters

前端 未结 7 1877
春和景丽
春和景丽 2021-02-02 11:05

Take the following classic factory pattern:

public interface IPizza
{
    decimal Price { get; }
}

public class HamAndMushroomPizza : IPizza
{
    decimal IP         


        
7条回答
  •  臣服心动
    2021-02-02 12:01

    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.

    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.

提交回复
热议问题