策略模式消除IF ELSE

问题描述:
在你的代码中是否会出现这种情况,用很多的if else语句来执行对应的功能模块,并且各个分支模块中共同的部分也还不少,当后续迭代量上来后,随之而来的模块分支可能也会增多,有什么方法可以消除分支吗?

public String sayHello(String type) {
        //不同的类型有不能的业务处理,导致if else太多太多。宝宝心里苦啊..........................................
        if ("rice".equals(type)){
            return "你好,大米";
        }else if ("wheat".equals(type)){
            return "你好,小麦";
        }else {
            return "我不认识你";
        }
    }

解决方案:
大家都是程序员,直接上代码吧。

@Component
public class StrategySelector {
    private Map<String, StrategyService> serviceMap;

//Spring会把所有StrategyService的实现类放到services这个变量中
    @Autowired
    public void setServices(List<StrategyService> services) {
       //java stream转换成map
        serviceMap = services.stream().collect(Collectors.toMap(StrategyService::getType, Function.identity(), (k1, k2) -> k2));
    }

    public StrategyService getService(String type) {
        return serviceMap.get(type);
    }
}
public interface StrategyService {
    String sayHello(String type);
    String getType();
}
@Service
public class WheatStrategyServiceImpl implements StrategyService {
    @Override
    public String sayHello(String type) {
        return "你好,小麦";
    }

    @Override
    public String getType() {
        return "wheat";
    }
}
@Service
public class RiceStrategyServiceImpl implements StrategyService {
    @Override
    public String sayHello(String type) {
        return "你好,大米";
    }

    @Override
    public String getType() {
        return "rice";
    }
}
@Service
public class OtherStrategyServiceImpl implements StrategyService {
    @Override
    public String sayHello(String type) {
        return "我不认识你";
    }

    @Override
    public String getType() {
        return "other";
    }
}
@RestController
@RequestMapping("/strategy")
public class StrategyController {

    @Resource
    private StrategySelector selector;

    @RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String process2(String type) {
        StrategyService service = selector.getService(type);
        return service.sayHello(type);
    }
}

完整代码参考:https://github.com/465919283/demo

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值