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.

Certifications & exams

Which exam comes next?

You can already practise for 19 exams, and 21 are up for a vote. See all certifications with their official information, cast your vote or suggest your exam.

See all certifications