يعني إيه؟
زي لما تختار طريقة الدفع في المتجر!
كاش، فيزا، أو انستاباي - كل واحدة ليها طريقتها 💳
الـ ShoppingCart هو الـ Context - بيستخدم Strategy للدفع بس مش عارف تفاصيلها.
العقد المشترك - كل طرق الدفع لازم يكون عندها pay().
كل طريقة دفع ليها implementation خاص - Cash, Visa, Instapay.
// Strategy Interface
class PaymentStrategy {
pay(amount) { throw "Must implement!"; }
}
// Concrete Strategies
class CashPayment extends PaymentStrategy {
pay(amount) { return `💵 Paid ${amount} EGP in cash`; }
}
class VisaPayment extends PaymentStrategy {
pay(amount) { return `💳 Paid ${amount} EGP via Visa - 2% fee applied`; }
}
class InstapayPayment extends PaymentStrategy {
pay(amount) { return `📱 Paid ${amount} EGP via Instapay - instant!`; }
}
// Context
class ShoppingCart {
constructor() { this.total = 0; }
setPaymentStrategy(strategy) {
this.paymentStrategy = strategy; // غيّر الـ Strategy!
}
checkout() {
return this.paymentStrategy.pay(this.total);
}
}
// Usage - سهل تغيير الـ Strategy!
const cart = new ShoppingCart();
cart.total = 500;
cart.setPaymentStrategy(new CashPayment());
cart.checkout(); // 💵 Paid 500 EGP in cash
cart.setPaymentStrategy(new VisaPayment());
cart.checkout(); // 💳 Paid 500 EGP via Visa