Java 策略模式实现编程实例:根据来源系统选择不同策略
'Java \u7B56\u7565\u6a21\u5f0f\u5b9e\u73b0\u7f16\u7a0b\u5b9e\u4f8b\uff1a\u6839\u636e\u6765\u6e90\u7cfb\u7edf\u9009\u62e9\u4e0d\u540c\u7b56\u7565'\u8fd9\u672c\u6587\u7ae0\u901a\u8fc7\u4e00\u4e2a\u5b9e\u4f8b\u793a\u8303\u4e86\u5982\u4f55\u4f7f\u7528\u004a\u0061\u0076\u0061\u7b56\u7565\u6a21\u5f0f\u6839\u636e\u4e0d\u540c\u7684\u6765\u6e90\u7cfb\u7edf\uff08\u0053\u0079\u0073\u0074\u0065\u006d\u0041\u548c\u0053\u0079\u0073\u0074\u0065\u006d\u0042\uff09\u9009\u62e9\u4e0d\u540c\u7684\u7b56\u7565\u8fdb\u884c\u5904\u7406\u3002\u7b56\u7565\u6a21\u5f0f\u5141\u8bb8\u4f60\u5b9a\u4e49\u4e00\u7cfb\u5217\u7b97\u6cd5\uff0c\u5c06\u6bcf\u4e2a\u7b97\u6cd5\u5c01\u88c5\u5230\u72ec\u7acb\u7684\u7c7b\u4e2d\uff0c\u5e76\u4f7f\u4ed6\u4eec\u53ef\u4ee5\u76f8\u4e92\u66ff\u6362\u3002\n\n\u9996\u5148\uff0c\u521b\u5efa\u4e00\u4e2a\u7b56\u7565\u63a5\u53e3\u548c\u4e24\u4e2a\u5177\u4f53\u7684\u7b56\u7565\u7c7b\uff1a\n\n```java// \u7b56\u7565\u63a5\u53e3public interface Strategy { void process();}
// SystemA\u7684\u7b56\u7565public class SystemAStrategy implements Strategy { @Override public void process() { System.out.println('SystemA\u7684\u5904\u7406\u903c\u8f91'); }}
// SystemB\u7684\u7b56\u7565public class SystemBStrategy implements Strategy { @Override public void process() { System.out.println('SystemB\u7684\u5904\u7406\u903c\u8f91'); }}
\n\n\u7136\u540e\uff0c\u521b\u5efa\u4e00\u4e2a\u7b56\u7565\u9009\u62e9\u5668\u7c7b\uff0c\u6839\u636e\u6765\u6e90\u7cfb\u7edf\u9009\u62e9\u4e0d\u540c\u7684\u7b56\u7565\uff1a\n\n```javapublic class StrategySelector { private Strategy strategy;
public StrategySelector(String sourceSystem) { if (sourceSystem.equals('SystemA')) { strategy = new SystemAStrategy(); } else if (sourceSystem.equals('SystemB')) { strategy = new SystemBStrategy(); } else { throw new IllegalArgumentException('\u672a\u77e5\u7684\u6765\u6e90\u7cfb\u7edf'); } }
public void process() { strategy.process(); }}
\n\n\u6700\u540e\uff0c\u53ef\u4ee5\u4f7f\u7528\u7b56\u7565\u9009\u62e9\u5668\u6765\u6839\u636e\u6765\u6e90\u7cfb\u7edf\u9009\u62e9\u4e0d\u540c\u7684\u7b56\u7565\u8fdb\u884c\u5904\u7406\uff1a\n\n```javapublic class Main { public static void main(String[] args) { StrategySelector selectorA = new StrategySelector('SystemA'); selectorA.process(); // \u8f93\u51fa\uff1aSystemA\u7684\u5904\u7406\u903c\u8f91
StrategySelector selectorB = new StrategySelector('SystemB'); selectorB.process(); // \u8f93\u51fa\uff1aSystemB\u7684\u5904\u7406\u903c\u8f91 }}
\n\n\u4e0a\u8ff0\u4ee3\u7801\u4e2d\uff0c\u6839\u636e\u6765\u6e90\u7cfb\u7edf\u7684\u4e0d\u540c\uff0c\u4f7f\u7528\u7b56\u7565\u6a21\u5f0f\u9009\u62e9\u4e0d\u540c\u7684\u7b56\u7565\u8fdb\u884c\u5904\u7406\u3002\u8fd9\u6837\u53ef\u4ee5\u65b9\u4fbf\u5730\u6839\u636e\u4e0d\u540c\u7684\u6765\u6e90\u7cfb\u7edf\u6269\u5c55\u65b0\u7684\u7b56\u7565\uff0c\u800c\u4e0d\u9700\u8981\u4fee\u6539\u539f\u6709\u7684\u4ee3\u7801\u3002
原文地址: https://www.cveoy.top/t/topic/pLZL 著作权归作者所有。请勿转载和采集!