我正在尝试实施战略模式,问题是我无法访问战略实施类中注入的任何依赖项,所以这是我的代码
支付策略界面
public interface PaymentStrategy {
public void processPayment(double amount);
}
支付策略接口实现
@ApplicationScoped
public class CreditCardStrategy implements PaymentStrategy {
@Inject
@RestClient
ApiExample apiExample
public void processPayment(double amount) {
apiExample.doSomething() **//NULL POINTER EXCEPTION**
// Process credit card payment
}
}
@ApplicationScoped
public class PayPalStrategy implements PaymentStrategy {
@Inject
Service service
public void processPayment(double amount) {
service.doSomething() **//NULL POINTER EXCEPTION**
// Process PayPal payment
}
}
支付策略工厂
public class PaymentStrategyFactory {
public PaymentStrategy getPaymentStrategy(String paymentMethod) {
if (paymentMethod.equals("creditcard")) {
return new CreditCardStrategy();
} else if (paymentMethod.equals("paypal")) {
return new PayPalStrategy();
} else {
throw new IllegalArgumentException("Invalid payment method: " + paymentMethod);
}
}
}
主要程序方法
String paymentMethod = "creditcard"; // Or "paypal"
PaymentStrategyFactory factory = new PaymentStrategyFactory();
PaymentStrategy paymentStrategy = factory.getPaymentStrategy(paymentMethod);
PaymentProcessor paymentProcessor = new PaymentProcessor(paymentStrategy);
paymentProcessor.processPayment(100.0); //NULL POINTER EXCEPTION CAUSED BY apiExample.doSomething()