springboot+策略模式+依赖注入
时间: 2023-12-01 11:42:47 浏览: 104
在Spring Boot中使用策略模式和依赖注入可以通过以下步骤实现:
1. 创建策略接口和多个实现类,例如:
```java
public interface PaymentStrategy {
void pay(double amount);
}
@Component
public class CreditCardPaymentStrategy implements PaymentStrategy {
@Override
public void pay(double amount) {
System.out.println("Paid " + amount + " using credit card.");
}
}
@Component
public class PayPalPaymentStrategy implements PaymentStrategy {
@Override
public void pay(double amount) {
System.out.println("Paid " + amount + " using PayPal.");
}
}
```
2. 创建一个策略工厂类,用于根据不同的条件返回不同的策略实现类,例如:
```java
@Component
public class PaymentStrategyFactory {
private final CreditCardPaymentStrategy creditCardPaymentStrategy;
private final PayPalPaymentStrategy payPalPaymentStrategy;
@Autowired
public PaymentStrategyFactory(CreditCardPaymentStrategy creditCardPaymentStrategy, PayPalPaymentStrategy payPalPaymentStrategy) {
this.creditCardPaymentStrategy = creditCardPaymentStrategy;
this.payPalPaymentStrategy = payPalPaymentStrategy;
}
public PaymentStrategy getPaymentStrategy(String paymentMethod) {
if ("creditCard".equalsIgnoreCase(paymentMethod)) {
return creditCardPaymentStrategy;
} else if ("payPal".equalsIgnoreCase(paymentMethod)) {
return payPalPaymentStrategy;
} else {
throw new IllegalArgumentException("Invalid payment method: " + paymentMethod);
}
}
}
```
3. 在需要使用策略的地方,注入策略工厂,并根据条件获取对应的策略实现类,例如:
```java
@RestController
public class PaymentController {
private final PaymentStrategyFactory paymentStrategyFactory;
@Autowired
public PaymentController(PaymentStrategyFactory paymentStrategyFactory) {
this.paymentStrategyFactory = paymentStrategyFactory;
}
@PostMapping("/pay")
public void pay(@RequestParam String paymentMethod, @RequestParam double amount) {
PaymentStrategy paymentStrategy = paymentStrategyFactory.getPaymentStrategy(paymentMethod);
paymentStrategy.pay(amount);
}
}
```
在上述代码中,我们使用了Spring Boot的依赖注入功能,将策略实现类注入到策略工厂中,并将策略工厂注入到控制器中。在控制器中,我们根据请求参数获取对应的策略实现类,并调用其方法完成支付操作。
阅读全文