策略模式如何使用的,在SpringBoot如何使用,示例
时间: 2024-03-10 20:48:24 浏览: 20
策略模式是一种行为设计模式,它允许在运行时选择算法的行为。它定义了一系列算法,使它们可以互换使用,而不会影响到使用它们的客户端。在Spring Boot中,我们可以使用策略模式来实现具有相同业务逻辑但不同实现方式的代码块。下面是一个示例:
首先,我们需要定义一个策略接口,例如:
```java
public interface PaymentStrategy {
boolean pay(double amount);
}
```
然后,我们需要实现这个接口的多个具体策略,例如:
```java
@Component
public class CreditCardStrategy implements PaymentStrategy {
@Override
public boolean pay(double amount) {
// 实现信用卡支付逻辑
return true;
}
}
@Component
public class PaypalStrategy implements PaymentStrategy {
@Override
public boolean pay(double amount) {
// 实现Paypal支付逻辑
return true;
}
}
```
接着,我们需要一个策略工厂类来根据客户端需要的策略类型创建具体策略对象:
```java
@Component
public class PaymentStrategyFactory {
private final Map<String, PaymentStrategy> strategies;
public PaymentStrategyFactory(List<PaymentStrategy> strategyList) {
this.strategies = strategyList.stream().collect(Collectors.toMap(PaymentStrategy::getClass.getSimpleName, s -> s));
}
public PaymentStrategy getStrategy(String strategyType) {
return this.strategies.get(strategyType);
}
}
```
最后,在客户端代码中,我们可以使用这个策略工厂类来获取相应的策略对象,并调用其方法:
```java
@Service
public class PaymentService {
private final PaymentStrategyFactory paymentStrategyFactory;
public PaymentService(PaymentStrategyFactory paymentStrategyFactory) {
this.paymentStrategyFactory = paymentStrategyFactory;
}
public boolean pay(String strategyType, double amount) {
PaymentStrategy paymentStrategy = paymentStrategyFactory.getStrategy(strategyType);
if (paymentStrategy == null) {
throw new IllegalArgumentException("Invalid payment strategy type: " + strategyType);
}
return paymentStrategy.pay(amount);
}
}
```
这样,我们就可以在运行时选择不同的支付策略,例如:
```java
@Autowired
PaymentService paymentService;
@Test
public void testPay() {
boolean result1 = paymentService.pay("CreditCardStrategy", 100.0);
boolean result2 = paymentService.pay("PaypalStrategy", 100.0);
}
```