来吧,用设计模式来干掉 if-else( 二 )


策略接口
/** * @Description: 回执处理策略接口 * @Auther: wuzhazha */public interface IReceiptHandleStrategy {    void handleReceipt(Receipt receipt);}策略接口实现类 , 也就是具体的处理者
public class Mt2101ReceiptHandleStrategy implements IReceiptHandleStrategy {    @Override    public void handleReceipt(Receipt receipt) {        System.out.println("解析报文MT2101:" + receipt.getMessage());    }}public class Mt1101ReceiptHandleStrategy implements IReceiptHandleStrategy {    @Override    public void handleReceipt(Receipt receipt) {        System.out.println("解析报文MT1101:" + receipt.getMessage());    }}public class Mt8104ReceiptHandleStrategy implements IReceiptHandleStrategy {    @Override    public void handleReceipt(Receipt receipt) {        System.out.println("解析报文MT8104:" + receipt.getMessage());    }}public class Mt9999ReceiptHandleStrategy implements IReceiptHandleStrategy {    @Override    public void handleReceipt(Receipt receipt) {        System.out.println("解析报文MT9999:" + receipt.getMessage());    }}策略上下文类(策略接口的持有者)
/** * @Description: 上下文类 , 持有策略接口 * @Auther: wuzhazha */public class ReceiptStrategyContext {    private IReceiptHandleStrategy receiptHandleStrategy;    /**     * 设置策略接口     * @param receiptHandleStrategy     */    public void setReceiptHandleStrategy(IReceiptHandleStrategy receiptHandleStrategy) {        this.receiptHandleStrategy = receiptHandleStrategy;    }    public void handleReceipt(Receipt receipt){        if (receiptHandleStrategy != null) {             receiptHandleStrategy.handleReceipt(receipt);           }    }}策略工厂
/** * @Description: 策略工厂 * @Auther: wuzhazha */public class ReceiptHandleStrategyFactory {    private ReceiptHandleStrategyFactory(){}    public static IReceiptHandleStrategy getReceiptHandleStrategy(String receiptType){        IReceiptHandleStrategy receiptHandleStrategy = null;        if (StringUtils.equals("MT2101",receiptType)) {            receiptHandleStrategy = new Mt2101ReceiptHandleStrategy();        } else if (StringUtils.equals("MT8104",receiptType)) {            receiptHandleStrategy = new Mt8104ReceiptHandleStrategy();        }        return receiptHandleStrategy;    }}客户端
public class Client {    public static void main(String[] args) {        //模拟回执        List<Receipt> receiptList = ReceiptBuilder.generateReceiptList();        //策略上下文        ReceiptStrategyContext receiptStrategyContext = new ReceiptStrategyContext();        for (Receipt receipt : receiptList) {            //获取并设置策略            IReceiptHandleStrategy receiptHandleStrategy = ReceiptHandleStrategyFactory.getReceiptHandleStrategy(receipt.getType());            receiptStrategyContext.setReceiptHandleStrategy(receiptHandleStrategy);            //执行策略            receiptStrategyContext.handleReceipt(receipt);        }    }}


推荐阅读