Spring通过InitializingBean代替多if-else判断

1.引进策略模式
定义一个接口:

public interface typeService {
  /**
   * 打包数据
   * @param typeName
   * @return
   */
  public Map<String, Object> pakgeWordData(String typeName);
}

然后写对应实现类:

publicclass oneService implements typeService {  
  
@Override  
public String pakgeWordData(String typeName) {  

    return null;
}

2.引入工厂模式,主要就是这里,在这里定义一个map,来保存策略中的实例。

public class TypeStrategyFactory {
    //定义一个map,来保存策略中的实例
    private static Map<String, TypeService> services = new ConcurrentHashMap<String,TypeService>();

    public  static TypeService getByQuestionType(String type){
        return services.get(type);
    }

    public static void register(String userType,TypeService typeService){
        Assert.notNull(userType,"questionType can't be null");
        services.put(userType,typeService);
    }
}

3.使用Spring Bean的注册,让上面1里面的实现类继承InitializingBean,每次bean启动的时候,都会实现afterPropertiesSet,在这里面调用工厂里面的register,将当前类注册到bean里面。

publicclass oneService implements TypeService,InitializingBean {  
  
@Override  
public String pakgeWordData(String typeName) {  

    return null;
}
@Override  
public void afterPropertiesSet() throws Exception {  
        TypeStrategyFactory.register(typeId,this);  
}

4.调用,先将试题类型传给工厂,工厂通过类型返回对应的类,然后用类调用对应的方法。

TypeStrategyFactory factory = TypeStrategyFactory.getByQuestionType(typeId);
String result = factory.pakgeWordData("typeName");

评论

暂无评论