Created
February 27, 2018 04:15
-
-
Save ythalorossy/7ede191f9d0fdeba1787f7337e229027 to your computer and use it in GitHub Desktop.
Observer Pattern in Typescript
This file contains hidden or 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 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 | |
// [email protected] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment