Strategy Pattern: Payment System Implementation
Fast recall
Quick revision
Core answer
PaymentStrategy contract and implement the payment behaviors that genuinely share it. A checkout service receives or selects a strategy through a small registry, factory, or injected map and delegates the payment operation. Keep provider-specific validation and results behind the contract, but do not force unlike workflows into one weak interface merely to remove every conditional.Interview-ready guide
Interview answer
For a payment Strategy, I first define a contract that the payment methods actually share, including a useful request and result rather than only a boolean.
authorize(request)` can return an authorization ID and status; a card strategy calls its gateway while a UPI strategy starts its own provider flow. The checkout service delegates through that interface, while a small factory, registry, or injected map selects the implementation near the boundary that reads the requested type. This keeps changing provider code out of checkout and makes each strategy testable.
I do not remove conditionals at any cost: cash on delivery or an asynchronous bank transfer may have different lifecycle states, so I model those differences instead of forcing them into a misleading common method.
Strategy Pattern: Payment System Implementation
Direct Answer
Define a PaymentStrategy contract and implement the payment behaviors that genuinely share it. A checkout service receives or selects a strategy through a small registry, factory, or injected map and delegates the payment operation. Keep provider-specific validation and results behind the contract, but do not force unlike workflows into one weak interface merely to remove every conditional.
Common Mistakes & Pitfalls
- Using only a boolean result: payment flows often need states, provider references, retry meaning, and detailed failures.
- Forcing different lifecycles together: immediate authorization and cash on delivery may not satisfy one simple contract.
- Putting provider implementation code in checkout: keep changing integration details in the strategy.
- Assuming selection vanishes: a boundary still maps the requested method to an allowed implementation.
- Sharing unsafe mutable strategy state: injected singleton strategies must handle concurrent calls correctly.
Check your understanding
Answer these without looking back at the article.
- Where should strategy selection happen in a Spring app — controller, service, or factory?
- How do you test each payment strategy in isolation?
- How do you handle an unknown payment method in the map lookup?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.