Java 设计模式(4)策略模式+工厂模式
- 上一篇
- 区别
-
维度 工厂模式 策略模式 设计目标 对象创建(创建型模式) 行为封装(行为型模式) 关注点 如何生成对象实例 如何动态替换算法逻辑 交互方式 黑盒操作(客户端不感知具体类) 白盒操作(客户端需指定策略) 典型场景 多数据库连接生成、UI组件库创建 支付方式切换、排序算法选择
-
- 使用
- 正常的策略工厂模式
- 说明
- 工厂模式负责对象创建(PaymentFactory)
- 策略模式负责算法替换(PaymentStrategy实现类)
- 上下文类连接两种模式,保持客户端代码稳定
- 新增支付方式只需扩展策略接口和工厂类
-
// 策略接口:定义支付算法 public interface PaymentStrategy { void pay(double amount); } // 具体实现策略:支付宝支付 public class AlipayStrategy implements PaymentStrategy { @Override public void pay(double amount) { System.out.println("支付宝支付:" + amount + "元"); } } // 具体实现策略:微信支付 public class WeChatStrategy implements PaymentStrategy { @Override public void pay(double amount) { System.out.println("微信支付:" + amount + "元"); } } // 工厂类:创建策略对象 public class PaymentFactory { public static PaymentStrategy createStrategy(String type) { switch (type.toLowerCase()) { case "alipay": return new AlipayStrategy(); case "wechat": return new WeChatStrategy(); default: throw new IllegalArgumentException("不支持的支付类型"); } } } // 策略执行上下文 public class PaymentContext { private PaymentStrategy strategy; public PaymentContext(PaymentStrategy strategy) { this.strategy = strategy; } public void executePayment(double amount) { strategy.pay(amount); } } class ClientDemo { public static void main(String[] args) { // 工厂创建策略对象 PaymentStrategy strategy = PaymentFactory.createStrategy("alipay"); // 上下文执行策略 PaymentContext context = new PaymentContext(strategy); context.executePayment(100.0); } }
- 说明
- 使用注解的策略工厂模式
-
// 枚举类定义支持的支付类型,作为策略选择的标识。 enum PaymentType { ALIPAY, WECHAT, UNIONPAY } // 自定义注解用于标记具体策略实现类,包含支付类型信息 Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface Strategy { PaymentType value(); } // 定义支付策略接口,使用@FunctionalInterface注解支持Lambda表达式 @FunctionalInterface public interface PaymentStrategy { void pay(double amount); } // 使用@Strategy注解标记支付宝策略,@Component实现Spring自动管理 @Strategy(PaymentType.ALIPAY) @Component public class AlipayStrategy implements PaymentStrategy { @Override public void pay(double amount) { System.out.println("支付宝支付:" + amount); } } // 工厂类自动收集所有策略实现,通过注解值建立映射关系 @Component public class StrategyFactory implements ApplicationContextAware { private Map<PaymentType, PaymentStrategy> strategyMap = new HashMap<>(); @Override public void setApplicationContext(ApplicationContext context) { Map<String, PaymentStrategy> beans = context.getBeansOfType(PaymentStrategy.class); beans.values().forEach(strategy -> { Strategy annotation = strategy.getClass().getAnnotation(Strategy.class); strategyMap.put(annotation.value(), strategy); }); } public PaymentStrategy getStrategy(PaymentType type) { return strategyMap.get(type); } } // 服务类通过工厂动态获取策略实例,实现支付处理 public class PaymentService { @Autowired private StrategyFactory factory; public void processPayment(PaymentType type, double amount) { PaymentStrategy strategy = factory.getStrategy(type); strategy.pay(amount); } }
-
- 正常的策略工厂模式
- 下一篇
- 下一篇标题
- 下一篇链接
本文来自博客园,作者:zwjvzwj,转载请注明原文链接:https://www.cnblogs.com/zwjvzwj/p/19003058