在Spring Boot应用中实现策略模式通常涉及以下几个步骤:
定义策略接口:
public interface PaymentStrategy { void pay(int amount); }
实现具体的策略类:
public class CreditCardPayment implements PaymentStrategy { @Override public void pay(int amount) { System.out.println("Paid " + amount + " using credit card."); } } public class PayPalPayment implements PaymentStrategy { @Override public void pay(int amount) { System.out.println("Paid " + amount + " using PayPal."); } } // 可以有其他的支付方式实现类
定义策略上下文:
public class PaymentContext { private PaymentStrategy paymentStrategy; public PaymentContext(PaymentStrategy paymentStrategy) { this.paymentStrategy = paymentStrategy; } public void executePayment(int amount) { paymentStrategy.pay(amount); } }
使用Spring Boot进行注入:
@Component
import org.springframework.stereotype.Component; @Component public class CreditCardPayment implements PaymentStrategy { @Override public void pay(int amount) { System.out.println("Paid " + amount + " using credit card."); } } @Component public class PayPalPayment implements PaymentStrategy { @Override public void pay(int amount) { System.out.println("Paid " + amount + " using PayPal."); } }
在服务中使用策略模式:
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class PaymentService { private final PaymentContext paymentContext; @Autowired public PaymentService(PaymentContext paymentContext) { this.paymentContext = paymentContext; } public void processPayment(int amount, String paymentMethod) { switch (paymentMethod) { case "creditCard": paymentContext.executePayment(amount, "creditCard"); break; case "payPal": paymentContext.executePayment(amount, "payPal"); break; // 可以添加其他支付方式的处理逻辑 default: throw new IllegalArgumentException("Invalid payment method: " + paymentMethod); } } }
这样,你就可以通过调用processPayment方法并传入相应的支付方式,实现对应策略的执行。Spring Boot会自动根据@Component注解进行依赖注入,将具体的支付策略类注入到PaymentContext中。
processPayment
PaymentContext
请注意,这只是一个简单的示例。在实际应用中,可能需要更复杂的逻辑来选择合适的支付策略。
原文链接:codingdict.net