SOLID PRINCIPLE #5

Dependency Inversion

عكس الاعتماديات

يعني إيه؟ زي الفيشة الكهربائية! اللابتوب مش بيعتمد على شاحن معين...
بيعتمد على الـ Interface (الفيشة) - أي شاحن يشتغل! 🔌

THE CONCEPT

مثال الفيشة 🔌

اعتمد على Abstraction مش Concrete ❌ Direct Dependency NotificationService High-Level EmailSender Concrete! مربوط بـ Email بس! ✅ Dependency Inversion NotificationService High-Level «interface» INotifier 📧 Email 📱 SMS 🔔 Push 💡 المفتاح: Abstraction في النص! High-Level (Service) يعتمد على Interface Low-Level (Email, SMS) يـ implement الـ Interface ✅ الاتنين بيعتمدوا على الـ Abstraction!

🔵 High-Level Module

الـ NotificationService - مش عايز يعرف هيبعت email ولا SMS. عايز بس INotifier يـ send()!

🟣 Abstraction (Interface)

INotifier - العقد بين الـ Service والـ Implementation. الاتنين بيعتمدوا عليه!

🟢 Low-Level Modules

Email, SMS, Push - كل واحد يـ implement الـ INotifier. سهل تضيف جديد!

الكود 💻

❌ Direct Dependency
class EmailSender {
  send(msg) { 
    console.log(`📧 Email: ${msg}`); 
  }
}

class NotificationService {
  constructor() {
    // ❌ مربوط بـ EmailSender!
    this.sender = new EmailSender();
  }
  
  notify(msg) {
    this.sender.send(msg);
  }
}

// ❌ عايز SMS؟ لازم تغير الكود!
✅ Dependency Injection
// Interface
class INotifier {
  send(msg) { throw "implement!"; }
}

class Email extends INotifier {
  send(msg) { return `📧 ${msg}`; }
}

class SMS extends INotifier {
  send(msg) { return `📱 ${msg}`; }
}

// ✅ بياخد الـ notifier من بره!
class NotificationService {
  constructor(notifier) {
    this.notifier = notifier;
  }
  notify(msg) {
    return this.notifier.send(msg);
  }
}

// سهل التبديل!
new NotificationService(new Email());
new NotificationService(new SMS());

جرب! 🎮

// اختار notifier وشوف DIP في العمل!

🏆 مبروك! خلصت SOLID

العودة للرئيسية