策略模式代替大量的if else

原代码

public class Example {

    public Double calRecharge(Double charge, RechargeTypeEnum type) {

        if (type.equals(RechargeTypeEnum.E_BANK)) {
return charge * 0.85;
} else if (type.equals(RechargeTypeEnum.BUSI_ACCOUNTS)) {
return charge * 0.90;
} else if (type.equals(RechargeTypeEnum.MOBILE)) {
return charge;
} else if (type.equals(RechargeTypeEnum.CARD_RECHARGE)) {
return charge + charge * 0.01;
} else {
return null;
}
}
}

通过设计模式和重构后的代码:

import strategy.RechargeTypeEnum;
public interface Strategy {
public Double calRecharge(Double charge ,RechargeTypeEnum type );
} import strategy.RechargeTypeEnum;
public class EBankStrategy implements Strategy{
@Override
public Double calRecharge(Double charge, RechargeTypeEnum type) {
return charge*0.85;
}
} package strategy.strategy;
import strategy.RechargeTypeEnum;
public class BusiAcctStrategy implements Strategy{
public Double calRecharge(Double charge, RechargeTypeEnum type) {
return charge*0.90;
}
}

策略模式场景对象

package strategy.strategy;
import strategy.RechargeTypeEnum;
public class Context {
private Strategy strategy;
public Double calRecharge(Double charge, Integer type) {
strategy = StrategyFactory.getInstance().creator(type);
return strategy.calRecharge(charge, RechargeTypeEnum.valueOf(type));
}
public Strategy getStrategy() {
return strategy;
} public void setStrategy(Strategy strategy) { this.strategy = strategy; }
}

策略工厂对象

public class StrategyFactory {
private static StrategyFactory factory = new StrategyFactory();
private StrategyFactory(){ }
private static Map strategyMap = new HashMap<>();
static{
strategyMap.put(RechargeTypeEnum.E_BANK.value(), new EBankStrategy());
strategyMap.put(RechargeTypeEnum.BUSI_ACCOUNTS.value(), new BusiAcctStrategy());
strategyMap.put(RechargeTypeEnum.MOBILE.value(), new MobileStrategy());
strategyMap.put(RechargeTypeEnum.CARD_RECHARGE.value(), new CardStrategy()); }
public Strategy creator(Integer type){
return strategyMap.get(type);
}
public static StrategyFactory getInstance(){
return factory;
}
}
上一篇:init.rc文件中面启动c++程序,通过jni调用java实现


下一篇:C#调用Java方法(详细实例)