大量的if else组成的代码,维护性和扩展性较差,可以使用策略模式来进行优化。
抽象的处理类:
public abstract class AbstractHandler { public abstract void handle(); public abstract String type(); }
具体的几个处理类:
@Component public class FreeHandler extends AbstractHandler { @Override public void handle() { System.out.println("免费用户业务开始。。。"); } @Override public String type() { return "free"; } } @Component public class NormalHandler extends AbstractHandler { @Override public void handle() { System.out.println("普通会员业务开始。。。"); } @Override public String type() { return "normal"; } } @Component public class HighHandler extends AbstractHandler { @Override public void handle() { System.out.println("高级会员业务开始。。。"); } @Override public String type() { return "high"; } } @Component public class SuperHandler extends AbstractHandler { @Override public void handle() { System.out.println("超级会员业务开始。。。"); } @Override public String type() { return "super"; } }
注册和管理各业务处理类:
@Component public class AbstractHandlerProcessor implements ApplicationContextAware { private ApplicationContext context; private Map<String, AbstractHandler> processorMap = new HashMap<>(); public AbstractHandler choose(String type) { AbstractHandler handler = map.get(type); if(null == handler) { throw new Exception("不支持的type类型,联系管理员。。。") } return handler; } @PostConstruct public void register() { Map<String, AbstractHandler> handlerMap = context.getBeansOfType(AbstractHandler.class); for(AbstractHandler handler : handlerMap.values()) { processorMap.put(handler.type(),handler); } } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.context=applicationContext; } }
测试数据:
@RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes=Application.class)// 指定spring-boot的启动类 public class HandlerTest { @Autowired private AbstractHandlerProcessor chooser; @Test public void test() throws Exception{ String type = "free"; AbstractHandler handler = chooser.choose(type); handler.handle(); } }
还可以使用注解的方式来实现:
@Autowired private Map<String, AbstractHandler > registedHandlers;
具体的处理类:
@Service("free") public class FreeHandler extends AbstractHandler { @Override public void handle() { System.out.println("免费用户业务开始。。。"); } }
可以用registedHandlers来直接使用:
AbstractHandler handler = registedHandlers.get("free"); handler.handle();