يعني إيه؟
زي لما تعمل Subscribe لـ قناة يوتيوب!
كل ما ينزل فيديو جديد، كل المشتركين بيتبعتلهم notification
🔔
القناة هي الـ Subject - بتحتفظ بقايمة المشتركين وبتبلغهم لما ينزل فيديو جديد.
المشتركين هم الـ Observers - بيستقبلوا الـ notifications تلقائياً لما الحالة تتغير.
الفايدة: Loose Coupling - القناة مش محتاجة تعرف تفاصيل عن المشتركين!
// Subject - القناة
class YouTubeChannel {
constructor(name) {
this.name = name;
this.subscribers = []; // قايمة المشتركين
}
// إضافة مشترك
subscribe(observer) {
this.subscribers.push(observer);
console.log(`${observer.name} subscribed!`);
}
// إزالة مشترك
unsubscribe(observer) {
this.subscribers = this.subscribers
.filter(s => s !== observer);
}
// إبلاغ كل المشتركين
notify(video) {
this.subscribers.forEach(sub => {
sub.update(video); // كل واحد يستقبل
});
}
uploadVideo(title) {
console.log(`📺 New video: ${title}`);
this.notify({ title, channel: this.name });
}
}
// Observer - المشترك
class Subscriber {
constructor(name) {
this.name = name;
}
// دي اللي بتتنفذ لما ينزل فيديو
update(video) {
console.log(`
🔔 ${this.name} received:
"${video.title}" from ${video.channel}
`);
}
}
// الاستخدام
const channel = new YouTubeChannel("Tech Arabic");
const ahmed = new Subscriber("أحمد");
const sara = new Subscriber("سارة");
channel.subscribe(ahmed);
channel.subscribe(sara);
// لما ينزل فيديو - الكل يعرف!
channel.uploadVideo("Observer Pattern شرح");
// 🔔 أحمد received...
// 🔔 سارة received...