【发布时间】:2017-07-21 20:18:41
【问题描述】:
我正在处理私人事务,我遇到了需要其他意见的问题。我有以下代码,我想在其中创建一个工厂模式来创建 PaymentStrategy 的新实例:
PaymentStrategy接口
public interface PaymentStrategy {
Optional<Payment> pay(String payerAccountNumber,
String sellerAccountNumber,
ProductOrder[] productOrder
);
}
EmployeePaymentStrategyimplementation 有两个依赖项
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");
}
}
【问题讨论】:
-
你不应该使用
new EmployeePaymentStrategywhich,而是调用你的DI框架来实例化EmployeePaymentStrategywhich bean的实例 -
感谢您的建议。我用你的提议更新了我的帖子。现在这段代码线程安全吗?
标签: java spring dependency-injection autowired factory-pattern