gpt4 book ai didi

java - 如何创建 DRYer 构造函数

转载 作者:行者123 更新时间:2023-12-01 06:52:50 24 4
gpt4 key购买 nike

有什么方法可以减少以下任何构造函数的重复吗? IE。仅使用一个构造函数或没有多个“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 循环将提供的配料添加到列表中,但我不确定如何迭代构造函数给出的值

最佳答案

使用可变参数,您可以使用任意数量的配料,并且不用担心构造函数内的情况,您可以将其视为列表

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);
}

关于java - 如何创建 DRYer 构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20503936/

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