Skip to content

Instantly share code, notes, and snippets.

@ythalorossy
Created February 27, 2018 04:15
Show Gist options
  • Save ythalorossy/7ede191f9d0fdeba1787f7337e229027 to your computer and use it in GitHub Desktop.
Save ythalorossy/7ede191f9d0fdeba1787f7337e229027 to your computer and use it in GitHub Desktop.
Observer Pattern in Typescript
interface IObserver {
update(): void;
}
interface IObservable {
add(observer: IObserver): void;
remove(Obsever: IObserver): void;
notify(): void;
}
class WeatherStation implements IObservable {
private observers: IObserver[] = []
constructor() {
setInterval(() => this.notify(), 1500);
}
add = (observer: IObserver): IObservable => {
this.observers.push(observer);
return this;
};
remove = (observer: IObserver): void => {
this.observers = this.observers.filter(obs => observer !== obs);
};
notify = (): void => this.observers.forEach(observer => observer.update());
getTemperature = (): Number => Math.random() * 1000;
}
class PhoneDisplay implements IObserver {
constructor(private weatherStation: WeatherStation) { }
update = (): void => console.log('[PhoneDisplay] temperature: ', this.weatherStation.getTemperature());
}
class HardwareDisplay implements IObserver {
constructor(private weatherStation: WeatherStation) { }
update = (): void => console.log('[HardwareDisplay] temperature: ', this.weatherStation.getTemperature());
}
// Annonymous Test Class
new class ObserverPatternTests {
run = () => {
const station: WeatherStation = new WeatherStation();
const phone: IObserver = new PhoneDisplay(station);
const hardware: IObserver = new HardwareDisplay(station);
station
.add(phone)
.add(hardware);
}
}().run();
// By Ythalo Rossy
// ythalorossy@gmail.com
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment