Let's assume we have a simple payment feature on an online shop. We want to manage different transactions with different processors of transactions:
- A transaction can be a payment or a refund.
- A processor of transactions can be Paypal or Payplug.
So we have the following classes:
class PaymentTransaction implements Transaction {
}
class RefundTransaction implements Transaction {
}
class PaypalProcessor implements Processor {
}
class PayplugProcessor implements Processor {
}
As suggested in this answer, we could use the following class which uses Strategy and polymorphism.
class PaymentProcessor {
private Processor processor;
private Transaction transaction;
public PaymentProcessor(Processor processor, Transaction transaction) {
this.processor = processor;
this.transaction = transaction;
}
public void processPayment() {
processor.process(transaction);
}
}
We assume the processor and the transaction to use are given from the database. I wonder how to create the PaymentProcessor
object.
It seems that an abstract factory class with only one method is still a valid Abstract Factory pattern. So, in this case I wonder if using Abstract Factory would be relevant.
- If yes, how to implement it?
- If no, should we use Factory Method pattern with a
PaymentProcessorFactory
class to createPaymentProcessor
with his two attributes according the details given from the database?
What is a best practice to use a Factory in this case?
Aucun commentaire:
Enregistrer un commentaire