1

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

1

3 Answers 3

11

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();
        }
        ...
    }
}
Sign up to request clarification or add additional context in comments.

6 Comments

I knew there had to be a design pattern for this! So the factory does just that then? Should I also make it static or there's a good reason to not do so?
+1: But it's specifically the Factory Method pattern. There are other factory patterns...
Right @DonRoby, I too mean factory method.
@Andreas, I would make it a member function as mostly these factories are dependencies either injected or located in an enterprise application.
So I should go with what @Eng.Fouad suggested?
|
3

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

1 Comment

If this is 'legit' then thats just fine! However @Vikdor Factory Pattern may be more appropriate for more complex cases, and a better practice in overall. +1 at both.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.