1. 工厂模式 (Factory Pattern)
核心目的:创建对象
专注于如何创建对象,隐藏对象创建的复杂细节。
典型实现:
java
// 产品接口
public interface Payment {
void pay(BigDecimal amount);
}
// 具体产品
public class WechatPay implements Payment {
public void pay(BigDecimal amount) {
System.out.println("微信支付: " + amount);
}
}
public class Alipay implements Payment {
public void pay(BigDecimal amount) {
System.out.println("支付宝: " + amount);
}
}
// 工厂类 - 负责创建对象
public class PaymentFactory {
public static Payment createPayment(PaymentType type) {
switch (type) {
case WECHAT_PAY:
return new WechatPay();
case ALIPAY:
return new Alipay();
default:
throw new IllegalArgumentException("不支持的支付类型");
}
}
}
// 使用
Payment payment = PaymentFactory.createPayment(PaymentType.WECHAT_PAY);
payment.pay(new BigDecimal("100.00"));
工厂模式使用Spring Bean的几种方式
方式1:工厂类本身是Spring Bean
java
@Component
public class PaymentFactory {
@Autowired
private WechatPay wechatPay;
@Autowired
private Alipay alipay;
@Autowired
private BankCardPay bankCardPay;
public Payment createPayment(PaymentType type) {
switch (type) {
case WECHAT_PAY:
return wechatPay; // 返回Spring管理的Bean
case ALIPAY:
return alipay;
case BANK_CARD:
return bankCardPay;
default:
throw new IllegalArgumentException("不支持的支付类型");
}
}
}
方式2:使用ApplicationContext
java
@Component
public class PaymentFactory {
@Autowired
private ApplicationContext applicationContext;
public Payment createPayment(PaymentType type) {
switch (type) {
case WECHAT_PAY:
return applicationContext.getBean(WechatPay.class);
case ALIPAY:
return applicationContext.getBean(Alipay.class);
case BANK_CARD:
return applicationContext.getBean(BankCardPay.class);
default:
throw new IllegalArgumentException("不支持的支付类型");
}
}
}
方式3:使用@Bean方法工厂(配置类方式)
java
@Configuration
public class PaymentConfig {
@Bean
@ConditionalOnProperty(name = "payment.wechat.enabled", havingValue = "true")
public WechatPay wechatPay() {
return new WechatPay();
}
@Bean
@ConditionalOnProperty(name = "payment.alipay.enabled", havingValue = "true")
public Alipay alipay() {
return new Alipay();
}
@Bean
public PaymentFactory paymentFactory(List<Payment> payments) {
return new PaymentFactory(payments);
}
}