Structural PatternsAdapter PatternMedium⏱️ ~3 min

Adapter Pattern in Payment Gateway Integration

Consider a payment processing system that needs to integrate multiple third-party payment gateways (PayPal, Stripe, Square). Each gateway has its own API with different method names and parameters. The Adapter Pattern allows uniform integration.

Scenario Requirements

Your application expects a consistent PaymentProcessor interface with processPayment(amount, currency) method. However, PayPal uses sendPayment(), Stripe uses charge(), and Square uses createTransaction(). Each has different parameter structures.

Design Solution

«interface»
PaymentProcessor
+ processPayment(amount, currency): Result
PayPalAdapter
- paypal: PayPalAPI
+ processPayment(): Result
StripeAdapter
- stripe: StripeAPI
+ processPayment(): Result
PayPalAPI
+ sendPayment(config): Status
StripeAPI
+ charge(token, cents): Response

Implementation Details

PayPalAdapter Translation:

processPayment(amount, currency):
  config = createPayPalConfig(amount, currency)
  status = paypal.sendPayment(config)
  return convertToResult(status)

StripeAdapter Translation:

processPayment(amount, currency):
  cents = convertToCents(amount, currency)
  token = createStripeToken()
  response = stripe.charge(token, cents)
  return convertToResult(response)

Client Usage

processor: PaymentProcessor
if userPreference == PAYPAL:
  processor = PayPalAdapter(new PayPalAPI())
else if userPreference == STRIPE:
  processor = StripeAdapter(new StripeAPI())

result = processor.processPayment(100.00, USD)
Interview Tip: In machine coding rounds, demonstrate how adding a new payment gateway (like Square) only requires creating a new adapter without modifying existing code. This showcases the Open-Closed Principle (OCP).

Benefits in This Domain:

First, the client code (checkout service) remains unchanged when adding new gateways. Second, each adapter encapsulates gateway-specific logic (authentication, error handling, response parsing). Third, testing becomes easier as you can mock the PaymentProcessor interface. Fourth, switching between gateways at runtime becomes trivial through configuration.

💡 Key Takeaways
Each payment gateway adapter implements common PaymentProcessor interface
Adapters translate between uniform interface and gateway-specific APIs
Client code depends only on PaymentProcessor abstraction
Adding new gateways requires only new adapter classes (Open-Closed Principle)
Encapsulates gateway-specific complexity like parameter conversion and error handling
📌 Examples
1PayPal's sendPayment() adapted to processPayment()
2Stripe's charge() adapted to processPayment()
3Currency conversion logic hidden in adapters
← Back to Adapter Pattern Overview