Java 创建单件工厂

Java 创建单件工厂,java,Java,我如何摆脱这里的if语句。 我正在使用反射。 请帮忙。提前感谢。您只是返回SearchInterface的实例吗?若然,原因为何: String fullName = PATH + "." + name; Class cl= Class.forName(fullName); if(name.equalsIgnoreCase("MobileSearch")){ if(msearchType==null){

我如何摆脱这里的
if
语句。
我正在使用反射。

请帮忙。提前感谢。

您只是返回SearchInterface的实例吗?若然,原因为何:

        String fullName = PATH + "." + name;
        Class cl= Class.forName(fullName);
        if(name.equalsIgnoreCase("MobileSearch")){
            if(msearchType==null){
                msearchType=(SearchInterface)cl.newInstance();
            }
            return msearchType;

        }
        if(name.equalsIgnoreCase("BookSearch")){
            if(bsearchType==null){
                bsearchType=(SearchInterface)cl.newInstance();
            }
            return bsearchType;

        }
希望有帮助。

使用地图:

String fullName = PATH + "." + name;

Class cl= Class.forName(fullName);                
if(searchType==null){                                
     searchType=(SearchInterface)cl.newInstance();
}                        
return searchType;

这将给你另一个视角


没有足够的代码来理解您想要的内容。什么是msearchtype和bsearchtype?您从何处获取名称?我只需要创建一个实例,即一个单实例,并且我有多个域。如我发布的代码片段所示,在创建实例之前,我检查每个域对象是否为空。我需要解决这一问题。请帮助。@Sam-使用Nicks解决方案它应该通过使用地图来解决您的问题。如果它不在映射中,则创建实例,并减少代码中If语句的数量。此外,如果将来添加更多SearchInterface类型,则无需更改代码,除非路径发生更改
if (!searchInstances.containsKey(name)) 
{
  searchInstances.put(
    name, 
    (SearchInterface)Class.forName(PATH + "." + name).newInstance()
  );
}

return searchInstances.get(name);