Reputation: 1366
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
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