工厂模式(使用Spring Bean)和 策略工厂模式 的区别

核心思想区别

  • 工厂模式使用Spring Bean :核心目的还是创建/获取对象 ,只是创建源从new变成了Spring容器。
  • 策略工厂模式 :核心目的是管理和路由已经存在的策略对象到不同的业务逻辑。

代码对比

工厂模式使用Spring Bean

typescript 复制代码
    
@Component
public class PaymentFactory {
    
    @Autowired
    private ApplicationContext applicationContext;
    
    /**
     * 核心:获取支付处理器对象
     * 关注点是"获取哪个对象"
     */
    public PaymentHandler getPaymentHandler(PaymentType type) {
        switch (type) {
            case WECHAT_PAY:
                return applicationContext.getBean(WechatPaymentHandler.class);
            case ALIPAY:
                return applicationContext.getBean(AlipayPaymentHandler.class);
            case BANK_CARD:
                return applicationContext.getBean(BankCardPaymentHandler.class);
            default:
                throw new IllegalArgumentException("不支持的支付类型");
        }
    }
}

// 使用方式:先获取对象,再执行业务
public class PaymentService {
    @Autowired
    private PaymentFactory paymentFactory;
    
    public void processPayment(PaymentRequest request) {
        // 1. 从工厂获取处理器对象
        PaymentHandler handler = paymentFactory.getPaymentHandler(request.getType());
        
        // 2. 使用处理器执行业务
        handler.validate(request);
        handler.pay(request);
        handler.record(request);
    }
}

策略工厂模式

typescript 复制代码
@Component
public class PaymentStrategyFactory {
    private final Map<PaymentType, PaymentStrategy> strategyMap;
    
    @Autowired
    public PaymentStrategyFactory(List<PaymentStrategy> strategies) {
        // Spring启动时自动收集所有策略
        strategyMap = strategies.stream()
            .collect(Collectors.toMap(PaymentStrategy::getType, Function.identity()));
    }
    
    /**
     * 核心:获取策略来执行特定算法
     * 关注点是"执行哪个算法"
     */
    public PaymentStrategy getStrategy(PaymentType type) {
        return strategyMap.get(type);
    }
}

// 使用方式:直接执行策略算法
public class PaymentService {
    @Autowired
    private PaymentStrategyFactory strategyFactory;
    
    public PaymentResult processPayment(PaymentRequest request) {
        // 直接获取策略并执行支付算法
        PaymentStrategy strategy = strategyFactory.getStrategy(request.getType());
        
        // 策略模式通常有统一的算法接口
        return strategy.pay(request.getAmount(), request);
    }
}

关键区别总结

方面 工厂模式使用Spring Bean 策略工厂模式
核心目的 对象创建和获取 算法选择和管理
关注点 "给我一个XX对象" "用XX策略处理这个问题"
方法签名 getXxxHandler() getXxxStrategy()
使用方式 获取对象后调用多个方法 获取策略后调用统一算法方法
接口设计 不同对象接口可能不同 所有策略有统一的算法接口
典型场景 需要不同对象处理完整业务流程 同一问题的不同算法解决方案

如何选择?

使用工厂模式+Spring Bean当:

  • 需要获取不同类型的处理器来处理完整业务流程
  • 不同处理器的方法签名或职责可能不同
  • 关注的是获取合适的对象来完成任务

使用策略工厂模式当:

  • 解决同一问题的不同算法变体
  • 所有策略都有相同的输入输出和职责
  • 关注的是选择和执行特定算法

实际项目中经常共存

java

scss 复制代码
@Service
public class OrderService {
    @Autowired
    private OrderHandlerFactory handlerFactory;      // 工厂模式:获取处理器
    @Autowired
    private PriceStrategyFactory strategyFactory;    // 策略工厂:获取计算策略
    
    public OrderResult createOrder(OrderRequest request) {
        // 工厂模式:获取订单处理器处理完整流程
        OrderHandler handler = handlerFactory.getHandler(request.getOrderType());
        Order order = handler.createOrder(request);
        
        // 策略工厂模式:使用特定策略计算价格
        PriceStrategy priceStrategy = strategyFactory.getStrategy(request.getPriceType());
        BigDecimal finalPrice = priceStrategy.calculate(order);
        order.setFinalPrice(finalPrice);
        
        return handler.completeOrder(order);
    }
}

简单来说:工厂关注"谁来做",策略工厂关注"怎么做" 。

相关推荐
XW20 分钟前
常用提示词(Prompt)框架总结
后端
ServBay27 分钟前
DeepSeek 再次崩了,DeepSeek V5正在路上?
后端·deepseek
IT规划师1 小时前
编程术语中的同步与异步:从"等不等"到工程取舍
后端·面试
孟陬2 小时前
Foobar 技术周刊#159:当看不懂代码时,如何高效排障调试。脏页陷阱:一条只读查询,写入数 TB 数据。推测解码:大模型加速利器
前端·人工智能·后端
GoGeekBaird2 小时前
别再给每个 AI 做自我介绍了:我做了一个「个人上下文」管理系统
后端·github·agent
码事漫谈2 小时前
腾讯混元 Hy4 正式版发布了
后端
Mikko72 小时前
Redis 连接数满了服务端有错误信息吗?连接数不增加却命令超时?6.2 实测连接池、超时与大 key 怎么判定
java·spring boot·redis·后端
苍何4 小时前
DeepSeek的Super-agent 设计,和我们的工程实践
后端
Patrick_Wilson4 小时前
第一次读 Go 项目:从两个源码文件弄清 package、import 和 go.mod
后端·go·编程语言
Patrick_Wilson4 小时前
执行 go build . 后,Go 怎样找到代码并生成程序
后端·go·编程语言