简体   繁体   中英

How to call a different constructor based on variable value in Java

Its a simple question really.

class salad
class chef_salad extends salad
class ceasar_salad extends salad

So I have a variable type and I want to create the appropriate object based on type.

Apparently I can do

if(type.equals("chef"){ salad s = new chef_salad(); }

I suppose I can even make that a static method that returns a salad object, but is this really the best approach or there is a better way to do it through constructors?

ps. fictional example

You are talking about Factory pattern where you want to hide the logic behind instantiating an object of a given type in an inheritance hierarchy, based on the inputs.

public class SaladFactory
{
    public Salad getSalad(type) {
        if ("chef".equals(type) {
            return new ChefSalad();
        }
        ...
    }
}

I would do it like this:

public static Salad createSaladInstance(String type)
{
    if(type.equals("Salad")) return new Salad();
    else if(type.equals("ChefSalad")) return new ChefSalad();
    // ...
}

// ...

Salad s = createSaladInstance(type);

See the Factory Design pattern .

public interface SaladFactory
   {
   public Salad createSalad();
   public String getName();
   }

for(SaladFactory factory:factories)
{
if(factory.getName().equals("caesar")) return facory.createSalad();
}

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