Strategy
TypeScriptApplicationTypeScript payment method strategies
Encapsulates card and PayPal payment behavior behind a shared interface so checkout selects a payment algorithm without branching through each method.
TypeScript
interface PaymentStrategy {
pay(amountInCents: number): Promise<void>;
}
class CardPayment implements PaymentStrategy {
async pay(amountInCents: number) {
console.log(`Charging card for ${amountInCents} cents`);
}
}
class PayPalPayment implements PaymentStrategy {
async pay(amountInCents: number) {
console.log(`Charging PayPal for ${amountInCents} cents`);
}
}
class CheckoutService {
constructor(private readonly paymentStrategy: PaymentStrategy) {}
checkout(amountInCents: number) {
return this.paymentStrategy.pay(amountInCents);
}
}