Created
July 14, 2024 13:14
-
-
Save md-shah/8f0208383e184cd4720cab03e721c36d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface Order { | |
order_id: string; | |
} | |
// ✅ Good | |
// Extending the payment service without modifying existing code (Open-Closed Principle) | |
abstract class PaymentGateway { | |
abstract processPayment(order: Order): void; | |
} | |
class CreditCardGateway extends PaymentGateway { | |
processPayment(order: Order): void { | |
console.log("// Process credit card payment for order: " + order.order_id); | |
} | |
} | |
class PayPalGateway extends PaymentGateway { | |
processPayment(order: Order): void { | |
console.log("// Process PayPal payment for order: " + order.order_id); | |
} | |
} | |
class BitcoinGateway extends PaymentGateway { | |
processPayment(order: Order): void { | |
console.log("// Process Bitcoin payment for order: " + order.order_id); | |
} | |
} | |
// Maybe you want to add support for a new payment Method 🤔 👇 | |
class ApplePayGateway extends PaymentGateway { | |
processPayment(order: Order): void { | |
console.log("// Process ApplePay payment for order: " + order.order_id); | |
} | |
} | |
enum PAYMENT_METHOD { | |
CREDIT_CARD = 'credit-card', | |
PAYPAL = 'paypal', | |
BITCOIN = 'bitcoin', | |
APPLE_PAY = 'apple-pay', // Added ApplePay to the enum | |
} | |
class PaymentService { | |
private paymentGateways: Record<string, PaymentGateway> = {}; | |
public registerPaymentGateway(paymentMethod: PAYMENT_METHOD, gateway: PaymentGateway) { | |
this.paymentGateways[paymentMethod] = gateway; | |
} | |
public async processPayment(order: Order, paymentMethod: PAYMENT_METHOD) { | |
const gateway = this.paymentGateways[paymentMethod]; | |
if (gateway) { | |
await gateway.processPayment(order); | |
} else { | |
throw new Error('Unsupported payment method!'); | |
} | |
} | |
} | |
// Create an order | |
const order: Order = { order_id: "12345" }; | |
// Initialize the payment service | |
const newPayment = new PaymentService(); | |
// Register payment gateways | |
newPayment.registerPaymentGateway(PAYMENT_METHOD.CREDIT_CARD, new CreditCardGateway()); | |
newPayment.registerPaymentGateway(PAYMENT_METHOD.PAYPAL, new PayPalGateway()); | |
newPayment.registerPaymentGateway(PAYMENT_METHOD.BITCOIN, new BitcoinGateway()); | |
newPayment.registerPaymentGateway(PAYMENT_METHOD.APPLE_PAY, new ApplePayGateway()); // Registering ApplePay | |
// Process a payment | |
newPayment.processPayment(order, PAYMENT_METHOD.PAYPAL); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment