Java 设计模式(4)策略模式+工厂模式

  1. 上一篇
    1. Java 设计模式(3)策略模式
  2. 区别
    1. 维度工厂模式策略模式
      设计目标 对象创建‌(创建型模式) 行为封装‌(行为型模式)
      关注点 如何生成对象实例‌ 如何动态替换算法逻辑‌
      交互方式 黑盒操作(客户端不感知具体类)‌ 白盒操作(客户端需指定策略)‌
      典型场景 多数据库连接生成、UI组件库创建‌ 支付方式切换、排序算法选择‌
  3. 使用
    1. 正常的策略工厂模式
      1. 说明
        1. 工厂模式负责对象创建(PaymentFactory)
        2. 策略模式负责算法替换(PaymentStrategy实现类)
        3. 上下文类连接两种模式,保持客户端代码稳定
        4. 新增支付方式只需扩展策略接口和工厂类
      2. // 策略接口:定义支付算法
        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);
            }
        }

         

    2. 使用注解的策略工厂模式
      1. // 枚举类定义支持的支付类型,作为策略选择的标识。
        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);
            }
        }

         

  4. 下一篇
    1. 下一篇标题
    2. 下一篇链接
posted @ 2025-07-24 16:23  zwjvzwj  阅读(11)  评论(0)    收藏  举报