//type为上文的参数 switch (type){ case 2: //逻辑处理 很长 看着难受 break; case 3: //逻辑处理 break; case 4: //逻辑处理 break; case 5: //逻辑处理 break; default: break; }
public interface Strategy { Type getType(); T doHandle(args...); }
@Component public class AStrategy implements Strategy { @Override public Type getType() { return TypeA; } @Override public T doHandle(args...) { //具体逻辑 return A; } }
@Component public class BStrategy implements Strategy { @Override public Type getType() { return TypeB; } @Override public T doHandle(args...) { //具体逻辑 return B; } }
//第一种 有新增的策略启动会自动加载进去 @Component public class StrategyHandler implements ApplicationContextAware{ private static Map<String,Strategy> map=new HashMap<>(); private static Map<Integer, Strategy> strategyMap=new HashMap<>(); @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { //根据接口类型返回相应的所有bean map = applicationContext.getBeansOfType(Strategy.class); } public static Map<Integer, Strategy> getMap() { if(map == null || map.isEmpty()){ return null; } for(String key: map.keySet()){ Object obj = map.get(key); if(!(obj instanceof Strategy)){ continue; } Strategy handler=(Strategy)obj; strategyMap.put(handler.getType().getCode(),handler); } return strategyMap; } }
//第二种,新增具体策略后需要修改 @Component public class StrategyHandler implements ApplicationContextAware{ private static StrategyFactory strategyFactory=new StrategyFactory(); private static Map<Integer,Strategy> map=new HashMap<>(); static { map.put(typeA,new AwardsVoucherStategy()); map.put(typeB,new AwardsVoucherStategy()); map.put(typeC,new AwardsVoucherStategy()); map.put(typeD,new AwardsVoucherStategy()); } public static StrategyFactory getInstance(){ return strategyFactory; } public Strategy getStrategyByType(Type type){ return map.get(type); }
//第一种使用: AwardsStrategyHandler.getMap().get(type).doHandle(args...); /第二种使用: StrategyHandler.getInstance().getStrategyByType(type).doHandle(args...);将不同情况 定义strategy接口 分别实现具体的实现类strategyA strategyB strategyC,每个类设置一个类型 在Context(StrategyHandler) 中 能获取到具体的类,再进行逻辑处理。