Design patterns · Question 9 of 12
A checkout service selects the payment method via switch, and every new payment method requires a change to this class. Which refactoring fits the open/closed principle?
1 answer is correct. Medium
Show answer
Answer
- A An interface PaymentProviderInterface with #[AutoconfigureTag('myext.payment')], one class per payment method, and #[AutowireIterator('myext.payment')] iterable $providers in the service
Explanation
The strategy pattern encapsulates each payment method in its own class with a common interface. Via the tag the container collects all implementations, and the service asks each one whether it is responsible. New payment methods, also from other extensions, are added without changing the service. An extracted switch or a collective class still has to be changed for every new method.