Created
April 8, 2022 22:39
-
-
Save vrogueon/34648e53b677456b744fd7cdd8b9f785 to your computer and use it in GitHub Desktop.
Observer Pattern TS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface IPublisher { | |
subscribe(observer: Observer): void | |
unsubscribe(observer: Observer): void | |
notify(news: String): void | |
} | |
interface IObserver { | |
update(news: string): void | |
} | |
class MoonsNews implements IPublisher { | |
private observers: Observer[] = []; | |
subscribe(observer: Observer) { | |
this.observers.push(observer); | |
} | |
unsubscribe(observer: Observer) { | |
this.observers = this.observers.filter(obs => obs !== observer); | |
} | |
notify(news: string) { | |
this.observers.forEach(obs => obs.update(news)); | |
} | |
} | |
class Observer implements IObserver { | |
constructor(public readonly name: string) { } | |
private feed: string[] = []; | |
update(news: string) { | |
this.feed.push(news); | |
console.log(`${this.name} recibió notificación`); | |
} | |
showFeed() { | |
console.log(this.name + ":" + this.feed); | |
return this.name + ":" + this.feed; | |
} | |
} | |
const patientMX = new Observer("Carlos"); | |
const patientCOL = new Observer("Juan Pa"); | |
const moonsNews = new MoonsNews(); | |
moonsNews.subscribe(patientMX); | |
moonsNews.subscribe(patientCOL); | |
moonsNews.notify("Ya hay moons hechos de nuevo material!"); | |
console.log(patientMX.showFeed()); | |
console.log(patientCOL.showFeed()); | |
moonsNews.unsubscribe(patientMX); | |
moonsNews.notify("Los moons eliminaron a los brackets!"); | |
console.log(patientMX.showFeed()); | |
console.log(patientCOL.showFeed()); | |
const patientPE = new Observer("Pablo"); | |
moonsNews.subscribe(patientPE); | |
console.log(patientPE.showFeed()); | |
moonsNews.notify("Nuevos moons de colores!"); | |
console.log(patientPE.showFeed()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment