1.问题
假如让你重构下面这段代码,你会如何实现?用代码说明。(注:后续可能会有type6,type7等,建议基于开闭原则重构。下面代码比较简明,实际工作中重构意义不是很大,目的是让大家掌握思想。)
public void method(int type) {
if(type==0){
doA();
}else if(type==1){
doB();
}else if(type==2){
doC();
}else if(type==3){
doD();
}else if(type==4){
doE();
}else if(type==5){
doF();
}
}
2.答案
使用策略模式,并交给Spring管理
2.1.定义策略接口
public interface Action {
public void doAction();
}
2.2.实现不同策略
@Component
public class Action1 implements Action {
@Override
public void doAction() {
System.out.println("=======Action1======");
}
}
@Component
public class Action2 implements Action {
@Override
public void doAction() {
System.out.println("=======Action2======");
}
}
2.3.实现抽象策略工厂,生成任意策略方法
public abstract class AbstractStrategyFactory<T> implements ApplicationContextAware, InitializingBean {
private Map<String,T> strategyContext;
private ApplicationContext applicationContext;
public T getStrategy(String strategyName){
return (T) this.strategyContext.get(strategyName);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext=applicationContext;
}
@Override
public void afterPropertiesSet() {
Class<T> strategyClass =(Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
this.strategyContext = this.applicationContext.getBeansOfType(strategyClass);
}
}
2.4.实现Action策略工厂
@Component
public class ActionFactory extends AbstractStrategyFactory<Action> {
}
2.5.测试
public static void main(String[] args) {
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(AppConfig.class);
ActionFactory af = ac.getBean(ActionFactory.class);
af.getStrategy("action1").doAction();
af.getStrategy("action2").doAction();
}
```