interface Observer{ update:() => void; } class ConcreteObserverA implements Observer { update() { console.log(this.constructor.name,"has been updated"); } } class ConcreteObserverB implements Observer { update () { console.log(this.constructor.name,"has been updated"); } } class Subject { private _name = ""; private observerCollection:Observer[] = []; get name() { return this._name; } set name(val:string) { this._name=val; this.notifyObservers(); } registerObserver(...o:Observer[]) { this.observerCollection.push(...o); } unregisterObserver(o:Observer) { this.observerCollection = this.observerCollection.filter (e => e! == o); } notifyObservers() { this.observerCollection.forEach(o => o.update() ); } } const subject = new Subject(); const oA = new ConcreteObserverA(); const oB = new ConcreteObserverB(); subject.registerObserver(oA, oB); subject.name = "Jau, jau!";
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter