KatInterview

Pluggable Payment Dispatch with Spring Bean Maps

Data Structure DesignModel answer
MediumModel answerData Structure Designjavaspringstrategy-pattern

Last updated

Design an extensible payment dispatcher in Spring where a Map of strategy beans is injected automatically and new payment methods need no changes to the service.

Build an Extensible Payment Dispatcher

An online store has to accept several payment methods, such as credit card, crypto, and possibly PayPal later. Design a small Spring-based component that routes a payment to the right handler without a growing chain of conditionals.

What to build

  1. A PaymentStrategy interface with a single operation, processPayment(double amount).
  2. Two implementations of it: CreditCardPayment and CryptoPayment.
  3. A PaymentService that keeps its strategies in a Map keyed by payment type. The map must be filled by Spring's dependency injection from all PaymentStrategy beans in the context, not by hand.
  4. A method executePayment(String type, double amount) on PaymentService. It finds the strategy registered for type and calls it with amount. If no strategy exists for type, it throws IllegalArgumentException.

Example

// Beans are managed by Spring
PaymentService service = ...;

// Finds the bean registered as "creditCard" and calls processPayment(100.0)
service.executePayment("creditCard", 100.0);

Discussion points

Be ready to explain:

  • How the design lets you add a new payment method without editing PaymentService (Open/Closed Principle).
  • Why a Map lookup is preferable to a long if-else or switch.
  • What role bean naming, autowiring, and @Qualifier play in making this work.
  • How the design relates to the Liskov Substitution Principle.

Provide the code and a clear explanation of your design choices.

Hints

Hint 1

Give each strategy a bean name through its stereotype annotation. When Spring injects a Map whose value type is your interface, it uses bean names as the keys.

Hint 2

The dispatcher should do one lookup and one null check, then delegate. It should never mention a concrete strategy class.

Hint 3

Think about what a caller must be able to assume about any PaymentStrategy, and where input validation should live so that no implementation tightens the contract.

Hint 4

Bean names become part of your public API. Consider what happens if someone renames a class, and whether an explicit type identifier on the interface would be safer.