在没有if-statments的情况下获取未知实现类的单例?

时间:2015-12-11 08:18:38

标签: java interface singleton implementation

我希望能够拨打未知实施类getInstance()。写if语句是唯一的解决方案吗?请参阅课程Main

public interface Soup{public Something getSomething();}

public class ChickenSoup implements Soup {
  private static ChickenSoup instance;
  public static ChickenSoup getInstance(){
    if (instance == null){
        instance = new ChickenSoup();
    }
    return instance;
  }
  public Something getSomething(){return Something something;}
}

public class OnionSoup implements Soup {
  private static OnionSoup instance;
  public static OnionSoup getInstance(){
    if (instance == null){
        instance = new OnionSoup();
    }
    return instance;
  }
  public Something getSomething(){
    Something something = somethingElse;
    return something;
  }
}

public class Main{
  private HashMap<String,Soup> soups;
  public Main(){
    buildMap();
  }
  public void callSoupClassGetInstance(String someSoupClassName){
    for (String impClass : soups.values()){
        if (someSoupClassName.contentEquals(impClass.simpleName())){
        //?????????????????????????????????????????

在这里,我希望能够获得实现类的实例,但我不能因为我必须能够知道我将它投射到并在我调用{{{{{{{{{ 1}}。 我是否可以在不制作一堆if语句来检查实现类名的情况下执行此操作? 换句话说,是唯一的解决方案吗?:

getInstance()

1 个答案:

答案 0 :(得分:0)

您可以像这样使用Java Reflections来调用名称为其的类的静态方法。

try {
    Class<?> clazz = Class.forName( "OnionSoup" );
    Method method = clazz.getMethod("getInstance");
    method.invoke(null);
} catch( ClassNotFoundException | NoSuchMethodException |  IllegalAccessException |InvocationTargetException |SecurityException ex) {
    ex.printStackTrace();
}