STRUCTURAL PATTERN

Bridge Pattern

نمط الجسر

يعني إيه؟ زي الريموت والتلفزيون - كل واحد بيتطور لوحده! 📺🎮
بيفصل الـ Abstraction عن Implementation! 🌉

THE CONCEPT

مثال الريموت والتلفزيون 📺

Bridge = Abstraction + Implementation منفصلين! Abstraction 🎮 Remote 🎮 BasicRemote 🎮✨ AdvancedRemote 🌉 Implementation 📺 Device 📺 TV 📻 Radio الـ Combinations الممكنة: 🎮 + 📺 🎮 + 📻 🎮✨ + 📺 🎮✨ + 📻 ✅ 4 combinations بدون code duplication!

🎮 Abstraction

الـ High-level interface زي الـ Remote - بيعرف يتعامل مع أي Device!

📺 Implementation

الـ Actual devices زي TV, Radio - كل واحد implementation مختلف!

🌉 Bridge

الـ Composition بدل Inheritance - الريموت عنده reference للـ Device!

الكود 💻

Bridge.js
// 📺 Implementation Interface
class Device {
  isEnabled() { throw "implement!"; }
  enable() { throw "implement!"; }
  disable() { throw "implement!"; }
  setVolume(vol) { throw "implement!"; }
}

// Concrete Implementations
class TV extends Device {
  constructor() { super(); this.on = false; this.volume = 50; }
  isEnabled() { return this.on; }
  enable() { this.on = true; return "📺 TV is ON"; }
  disable() { this.on = false; return "📺 TV is OFF"; }
  setVolume(vol) { this.volume = vol; return `📺 Volume: ${vol}`; }
}

class Radio extends Device {
  constructor() { super(); this.on = false; this.volume = 30; }
  isEnabled() { return this.on; }
  enable() { this.on = true; return "📻 Radio is ON"; }
  disable() { this.on = false; return "📻 Radio is OFF"; }
  setVolume(vol) { this.volume = vol; return `📻 Volume: ${vol}`; }
}

// 🎮 Abstraction
class Remote {
  constructor(device) {
    this.device = device; // 🌉 Bridge!
  }
  togglePower() {
    return this.device.isEnabled() 
      ? this.device.disable() 
      : this.device.enable();
  }
  volumeUp() {
    return this.device.setVolume(this.device.volume + 10);
  }
}

// Refined Abstraction
class AdvancedRemote extends Remote {
  mute() {
    return this.device.setVolume(0) + " (Muted!)";
  }
}
Usage.js
// 🎯 Mix and match!
const tv = new TV();
const radio = new Radio();

// Basic remote + TV
const basicTVRemote = new Remote(tv);
console.log(basicTVRemote.togglePower()); // 📺 TV is ON
console.log(basicTVRemote.volumeUp());    // 📺 Volume: 60

// Advanced remote + Radio
const advRadioRemote = new AdvancedRemote(radio);
console.log(advRadioRemote.togglePower()); // 📻 Radio is ON
console.log(advRadioRemote.mute());        // 📻 Volume: 0 (Muted!)

// ✅ 4 combinations, no code duplication!
// Remote + TV, Remote + Radio
// AdvancedRemote + TV, AdvancedRemote + Radio

جرب! 🎮

🎮 Remote Type

📺 Device Type

📺

OFF

// اختار Remote و Device!
Adapter Composite