Node.js › Architecture & Design Patterns

What is the Strategy pattern, and how would you apply it to support multiple payment providers in a Node.js checkout service?

Intermediate

Answer

The Strategy pattern defines a family of interchangeable algorithms behind a common interface, letting the calling code select and swap the concrete implementation at runtime without changing its own logic -- for a checkout service supporting Stripe, PayPal, and bank transfers, each provider implements the same processPayment() interface, and the checkout flow simply calls whichever strategy was selected based on the customer's chosen payment method.
class StripeStrategy { async pay(amount) { return stripeClient.charge(amount); } }
class PayPalStrategy { async pay(amount) { return paypalClient.createPayment(amount); } }

class Checkout {
  constructor(paymentStrategy) { this.strategy = paymentStrategy; }
  async completeOrder(amount) { return this.strategy.pay(amount); }
}

new Checkout(new StripeStrategy()).completeOrder(4999);
Real-world example An online store adds Apple Pay support months after launch by writing a single new ApplePayStrategy class implementing the existing pay() interface, without touching the Checkout class or any of the other existing payment strategies at all.

Common follow-ups: How does the Strategy pattern differ from simply using an if/else chain based on payment type?;How would you make the choice of strategy configurable per merchant rather than hardcoded?