简体   繁体   中英

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.

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.

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.


And you can combine them using 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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM