Careeroza
Real World Example
Pluggable Payment Providers
Checkout services at companies like Swiggy or BookMyShow support several payment providers and switch between them. An interface defines the contract, an abstract base adds shared logging and validation, and each provider is a small class.
Example
interface PaymentProvider {
readonly name: string;
pay(orderId: string, amountPaise: number): string;
}
abstract class BaseProvider implements PaymentProvider {
abstract readonly name: string;
private static count = 0;
pay(orderId: string, amountPaise: number): string {
if (amountPaise <= 0) throw new Error("Invalid amount");
BaseProvider.count++;
const ref = this.process(orderId, amountPaise);
return `#${BaseProvider.count} ${this.name} ${orderId} Rs. ${(amountPaise / 100).toFixed(2)} ref=${ref}`;
}
protected abstract process(orderId: string, amountPaise: number): string;
}
class UpiProvider extends BaseProvider {
readonly name = "UPI";
protected process(orderId: string) { return "upi_" + orderId.toLowerCase(); }
}
class CardProvider extends BaseProvider {
readonly name = "CARD";
#secret = "sk_test";
protected process(orderId: string, amount: number) { return this.#secret.length + "_" + amount; }
}
const providers: Record<string, PaymentProvider> = { upi: new UpiProvider(), card: new CardProvider() };
console.log(providers.upi.pay("OD-501", 34900));
console.log(providers.card.pay("OD-502", 129900));Output
#1 UPI OD-501 Rs. 349.00 ref=upi_od-501 #2 CARD OD-502 Rs. 1299.00 ref=7_129900