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
Implementation Details
PayPalAdapter Translation:
config = createPayPalConfig(amount, currency)
status = paypal.sendPayment(config)
return convertToResult(status)
StripeAdapter Translation:
cents = convertToCents(amount, currency)
token = createStripeToken()
response = stripe.charge(token, cents)
return convertToResult(response)
Client Usage
if userPreference == PAYPAL:
processor = PayPalAdapter(new PayPalAPI())
else if userPreference == STRIPE:
processor = StripeAdapter(new StripeAPI())
result = processor.processPayment(100.00, USD)
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.