[英]How can I make a constructor that contains a number of the same objects but if one its empty to ignore it?
I want to make a constructor for a wrap that contains four fillings, but if one filling is empty (for example only 2 or 3 used instead of 4) to execute the code without any problem. 我想为包含四个填充的包装创建一个构造函数,但是如果一个填充为空(例如只使用2或3而不是4)来执行代码而没有任何问题。
I currently can only include only one filling with this code. 我目前只能使用此代码只包含一个填充。
Wrap one=new Wrap( new Bread("Italian"), new Filling("Ham"),new Topping("Cheddar"));
With your current constructor, you can only have zero ( null
) or one bread, filling and topping. 使用当前的构造函数,您只能有零( null
)或一个面包,填充和顶部。
You'll want to overload your constructor to allow for more input options. 您需要重载构造函数以允许更多输入选项。
If you want to have more than one filling and at most one topping, add this constructor 如果您想要多个填充并且最多只有一个顶部,请添加此构造函数
Wrap(Bread b, List<Filling> fillings, Topping topping)
If you want to have more than one filling and topping, then this 如果你想要有多个填充和浇头,那么这个
Wrap(Bread b, List<Filling> fillings, List<Topping> toppings)
Or just allow for the last case, and use Collections.singletonList()
for lists of one item. 或者只允许最后一种情况,并使用Collections.singletonList()
来获取一个项目的列表。
And you can combine them using this()
. 你可以使用this()
组合它们。
Summing up, this is an example 总结一下,这就是一个例子
Bread bread;
List<Filling> fillings;
List<Topping> toppings;
public Wrap(Bread b, List<Filling> fillings, List<Topping> toppings) {
// ...
}
public Wrap(Bread b, Filling f, Topping t) {
this(b, Collections.singletonList(f), Collections.singletonList(t));
}
public Wrap(Bread b, List<Topping> toppings) {
// Is this a pizza?
this(b, null, toppings);
}
I would suggest a constructor that takes a list of fillings, that way you can have a single constructor and it forces the caller to provide the list, even if it is empty. 我建议使用一个构造函数来获取填充列表,这样你就可以拥有一个构造函数,并强制调用者提供列表,即使它是空的。 This would allow any number of fillings. 这将允许任何数量的填充。
If 4 is the maximum, then the caller could pass in null
for each unused argument. 如果4是最大值,则调用者可以为每个未使用的参数传入null
。
If the fillings have a common base class, then the list can have the base class as its type. 如果填充具有公共基类,则列表可以将基类作为其类型。 (Or, Object if you must go that far, although that doesn't seem like a good idea.) The alternative is to use Varargs with the base class. (或者,对象,如果你必须走得那么远,虽然这似乎不是一个好主意。)另一种方法是使用Varargs与基类。
The messy way would be to produce a bunch of constructors offering all the combinations of arguments, but that has a bad "code smell" about it if you have this number of arguments. 凌乱的方法是生成一堆构造函数,提供所有参数组合,但如果你有这么多的参数,它就会有一个糟糕的“代码味道”。
The right answer depends on the interface you are trying to provide and how you would expect it to be used. 正确的答案取决于您尝试提供的界面以及您希望如何使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.