vendredi 21 juillet 2017

Factory Pattern when Constructor of the Implementation has Dependencies to Inject

I'm working on a private stuff and I faced an issue where I need other opinion. I have the following code where I want to make a factory pattern the create new instance of PaymentStrategy:

PaymentStrategy which is fine.

public interface PaymentStrategy {

  Optional<Payment> pay(String payerAccountNumber,
                        String sellerAccountNumber,
                        ProductOrder[] productOrder
  );
}

EmployeePaymentStrategywhich has two dependencies

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) {
    ...
  }
}

PaymentStrategyFactory where I have the issue

public class PaymentStrategyFactory {

  @Autowired
  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");
  }

I want to know how to deal with dependencies in a Factory class. Is the EmployeePaymentStrategy class the right place to inject those two dependencies? Is the Factory Pattern is best way to solve problem

Aucun commentaire:

Enregistrer un commentaire