有什么办法可以减少以下任何构造函数的重复性?即只使用一个构造函数或没有多个“ topping.add”调用?我的目标是要有一个披萨,可以有1个,2个或3个不同的浇头
private PizzaBase base;
List<PizzaTopping> toppings = new ArrayList<PizzaTopping>();
public Pizza(PizzaBase base, PizzaTopping topping) //Constructor for pizza with 1 topping
{
setBase (base);
toppings.add(topping);
}
public Pizza(PizzaBase base, PizzaTopping topping, PizzaTopping topping2) //Constructor for pizza with 2 toppings
{
setBase (base);
toppings.add(topping);
toppings.add(topping2);
}
public Pizza(PizzaBase base, PizzaTopping topping, PizzaTopping topping2, PizzaTopping topping3) //Constructor for pizza with 3 toppings
{
setBase (base);
toppings.add(topping);
toppings.add(topping2);
toppings.add(topping3);
}
最初,我考虑使用for循环将提供的浇头添加到列表中,但是我不确定如何遍历构造函数提供的值
最佳答案
使用varargs,您可以根据需要使用任意多个浇头,而不必担心在构造函数中使用它,您可以将其视为一个列表
private PizzaBase base;
List<PizzaTopping> toppings = new ArrayList<PizzaTopping>();
public Pizza(PizzaBase base, PizzaTopping... toppings) //Constructor for pizza with 1 topping
{
setBase (base);
for(PizzaTopping topping : topings)
toppings.add(topping);
}