我正在处理私人事务,我遇到了一个需要其他意见的问题。我有以下代码,我想在工厂模式中创建PaymentStrategy
的新实例:
PaymentStrategy
接口public interface PaymentStrategy {
Optional<Payment> pay(String payerAccountNumber,
String sellerAccountNumber,
ProductOrder[] productOrder
);
}
EmployeePaymentStrategy
实现,它有两个依赖项public class EmployeePaymentStrategy implements PaymentStrategy {
private final ProfileRemoteProvider profileRemoteProvider;
private final PaymentValidator paymentValidator;
@Autowired
public EmployeePaymentStrategy(ProfileRemoteProvider profileRemoteProvider,
PaymentValidator paymentValidator) {
this.profileRemoteProvider = profileRemoteProvider;
this.paymentValidator = paymentValidator;
}
@Override
public Optional<Payment> pay(String payerAccountNumber,
String sellerAccountNumber,
ProductOrder[] productOrder) {
...
}
}
我想知道如何处理Factory类中的依赖项。
EmployeePaymentStrategy
类是注入这两个依赖项的正确位置吗?
工厂模式是解决问题的最佳方式
PaymentStrategyFactory
我遇到问题public class PaymentStrategyFactory {
private PaymentStrategyFactory() {
}
public static PaymentStrategy getPaymentStrategy(AccountType payerAccountType,
AccountType sellerAccountType) {
if (sellerAccountType == AccountType.COMPANY) {
switch (payerAccountType) {
case EMPLOYEE:
return new EmployeePaymentStrategy(...); //TODO
case BASIC_USER:
return ...
default:
//this exception is throw when a payer account type is unknown
throw new RuntimeException("exception type will be more specific");
}
}
//This exception is throw when a seller account type is not a seller
throw new RuntimeException("exception type will be more specific");
}
}
答案 0 :(得分:0)
PaymentStrategyFactory
更新和工作public class PaymentStrategyFactory {
private static ApplicationContext context;
private ApplicationContext applicationContext;
@Autowired
private PaymentStrategyFactory(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
@PostConstruct
private void initializeApplicationContext() {
PaymentStrategyFactory.context = applicationContext;
this.applicationContext = null;
}
@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {
PaymentStrategyFactory.context = context;
}
public static PaymentStrategy getPaymentStrategy(AccountType payerAccountType,
AccountType sellerAccountType) {
if (sellerAccountType == AccountType.COMPANY) {
switch (payerAccountType) {
case EMPLOYEE:
return context.getBean(EmployeePaymentStrategy.class);
// return new EmployeePaymentStrategy();
case BASIC_USER:
...
}
}
throw ...
}
}
除了以下Ilya的评论之外,this post帮助我在使用Spring for DI(Dependencies Injection)时处理静态成员。现在一切对我来说都很好。