码迷,mamicode.com
首页 > 其他好文 > 详细

策略模式代替大量的if else

时间:2015-06-18 16:56:21      阅读:262      评论:0      收藏:0      [点我收藏+]

标签:

原代码

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;
    }
} 

 

策略模式代替大量的if else

标签:

原文地址:http://www.cnblogs.com/rigid/p/4585906.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!