/*
The Observer pattern is a design pattern lets you define a subscription
mechanism to notify multiple objects and it's used in the event driven
programming paradigm.
*/
class Subject {
private observers: Observer[] = [];
public subscribe(observer: Observer) {
this.observers.push(observer);
}
public unsubscribe(observer: Observer) {
const index = this.observers.indexOf(observer);
this.observers.splice(index, 1);
}
public notify(data: any) {
this.observers.forEach(observer => observer.update(data));
}
}
class Observer {
public update(data: any) {
console.log(data);
}
}
const subject = new Subject();
const observer = new Observer();
subject.subscribe(observer);
subject.notify('Hello World');
subject.unsubscribe(observer);