HsnVahedi
HsnVahedi

Reputation: 1366

get instance of sub-classes without if else or reflection or switch-case

Hi I have an abstract super class Fruit and some sub-classes Apple, Orange, ...

abstract class Fruit {
  public abstract String getFruitName();
  public static Fruit getInstance(String fruitName) {}
}

class Apple extends Fruit {
  public String getFruitName() {return "Apple";}
}

And other Fruit sub-classes are the same as Apple. I want to implement the getInstance method of Fruit so that for example for the parameter "Apple" it returns an Apple object. But i don't want to use reflection and I don't want to check it by if-else or switch-case. How can I do this?

Upvotes: 1

Views: 1007

Answers (3)

Karthik
Karthik

Reputation: 5040

You should look at Factory Pattern.

This is a clean approach, easy to maintain and produces readable code. Adding or removing a Fruit is also easy, Just remove the class and remove it from FruitFactory hashmap.

Create an Interface : Fruit

 public interface Fruit {
    void getFruitName();
 }

Create a Factory which returns correct Fruit according to your value. Instead of your if-else now you can just use the following :

  Fruit fruit = FruitFactory.getFruit(value);
  fruit.getFruitName();

One common way to write FilterFactory is using a HashMap inside it.

public class FilterFactory{
   static HashMap<String, Fruit> fruitMap;
   static{
       fruitMap = new HashMap<>();
       fruitMap.put("apple",new Apple());
       ...
   }
   // this function will change depending on your needs
   public Filter getFruit(int value){
       return fruitMap.get(value);
   }

}

Create your three(in your case) Fruits like this: (With meaningful names though)

public class Apple implements Fruit {

    public void getFruitName(){
      //do something
    }
}

EDIT : I see that the interface name Fruit clashes with your abstract class Fruit. You can use any name, I was just explaining the idea.

Upvotes: 0

kswaughs
kswaughs

Reputation: 3087

see this factory design pattern without if-else

Upvotes: 1

Daniel Jipa
Daniel Jipa

Reputation: 888

Use a switch for fruit name if you use java 7+

Upvotes: 0

Related Questions