策略接口
/** * @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); } }}
推荐阅读
- 经常用Redis,你知道主从复制吗?
- 在Linux系统上安装和使用dig和nslookup命令
- 用elastic-job-lite玩转SpringBoot定时器管理
- 滇红茶史追溯介绍,金丝滇红茶的功效与作用
- 冲泡绿茶用什么器具,蜜梨绿茶的做法
- 茶器的实用性与美感,关于紫砂壶的实用性使用功能
- 杜仲功效与作用是什么,七福饮的功效与作用
- 淳安大方茶品质特点,淳安大方茶功效与作用
- 茶的功效与作用禁忌,胖大海的禁忌与功效作用
- 茶渣的好用处,茶的环保生活茶渣妙用二