我有几个扩展 bean 的对象:
public class Fruit {}
public class Banana extends Fruit {}
public class Pear extends Fruit {}
而且我有一个具有不同实现的接口,每个 bean 一个。
public interface Milkshake {
public String doMilkshake();
}
public class FruitMilkshake implements Milkshake {
public String doMilkshake() {
return "Fruit Milkshake!";
}
}
public class BananaMilkshake implements Milkshake {
public String doMilkshake() {
return "Banana Milkshake!";
}
}
public class PearMilkshake implements Milkshake {
public String doMilkshake() {
return "Pear Milkshake!";
}
}
如何根据我的 bean 的具体类型实例化正确的实现?
现在我已经使用了类型化和 Map 来“映射”正确的实现。像这样:
public void hungry(Fruit fruit) {
Map<String, String> obj2impl = new HashMap<String, String>();
obj2impl.put("Fruit", "FruitMilkshake");
obj2impl.put("Banana", "BananaMilkshake");
obj2impl.put("Pear", "PearMilkshake");
String name = fruit.getClass().getCanonicalName();
String implName = obj2impl.get(name);
Milkshake milkshake = (Milkshake) Class.forName(implName).newInstance();
milkshake.doMilkshake(fruit);
}
public interface Milkshake <T t> {
public String doMilkshake(T t);
}
public class FruitMilkshake implements Milkshake<Fruit> {
public String doMilkshake(Fruit fruit) {
return "Fruit Milkshake!";
}
}
public class BananaMilkshake implements Milkshake<Banana> {
public String doMilkshake(Banana banana) {
return "Banana Milkshake!";
}
}
public class PearMilkshake implements Milkshake<Pear> {
public String doMilkshake(Pear pear) {
return "Pear Milkshake!";
}
}
更好的方法来实现这一目标?