BEHAVIORAL PATTERN

Strategy Pattern

نمط الاستراتيجية

يعني إيه؟ زي لما تختار طريقة الدفع في المتجر!
كاش، فيزا، أو انستاباي - كل واحدة ليها طريقتها 💳

THE CONCEPT

مثال الدفع 💳

غيّر طريقة الدفع وقت التشغيل 🛒 ShoppingCart (Context) «interface» PaymentStrategy pay(amount) 💵 CashPayment 💳 VisaPayment 📱 InstapayPayment ✅ غيّر الـ Strategy وقت الـ Runtime - بدون تعديل الكود!

🛒 Context

الـ ShoppingCart هو الـ Context - بيستخدم Strategy للدفع بس مش عارف تفاصيلها.

🎯 Strategy Interface

العقد المشترك - كل طرق الدفع لازم يكون عندها pay().

💳 Concrete Strategies

كل طريقة دفع ليها implementation خاص - Cash, Visa, Instapay.

الكود 💻

Strategy.js
// 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

جرب! 🎮

// اختار طريقة الدفع!
Observer Command