代码之美:多个if...else怎么优化

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();
    }
​```



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

左林右李02

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值