Created
November 25, 2017 22:18
-
-
Save Kamilnaja/c3ef415e5407c7704ad0384590140490 to your computer and use it in GitHub Desktop.
Observer pattern using 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 Subject { | |
registerObserver(o: Observer): void; | |
removeObserver(o: Observer): void; | |
notifyObservers(): void; | |
} | |
interface Observer { | |
update(temperature: number): void; | |
} | |
class WeatherStation implements Subject { | |
private temperature: number; | |
private observers: Observer[] = []; | |
setTemperature(temp: number){ | |
console.log(`WeatherStation: new temperature measurement ` + temp); | |
this.temperature = temp; | |
this.notifyObservers(); | |
} | |
public registerObserver(o: Observer) { | |
this.observers.push(o); | |
} | |
public removeObserver(o: Observer) { | |
let index = this.observers.indexOf(o); | |
this.observers.splice(index, 1); | |
} | |
public notifyObservers() { | |
for (let observer of this.observers) { | |
observer.update(this.temperature); | |
} | |
} | |
} | |
class TemperatureDisplay implements Observer { | |
private subject: Subject; | |
constructor(weatherStation: Subject) { | |
this.subject = weatherStation; | |
weatherStation.registerObserver(this); | |
} | |
public update(temperature: number) { | |
console.log(`Temperature display, i need to update my display`); | |
} | |
} | |
class Fan implements Observer { | |
private subject: Subject; | |
constructor(weatherStation: Subject) { | |
this.subject = weatherStation; | |
weatherStation.registerObserver(this); | |
} | |
public update(temperature: number) { | |
if (temperature > 25) { | |
console.log(`I am fan and i need to enable`); | |
} else { | |
console.log(`I am fan and i need to disable`) | |
} | |
} | |
} | |
let weatherStation = new WeatherStation(); | |
let tempDisplay = new TemperatureDisplay(weatherStation); | |
let fan = new Fan(weatherStation); | |
weatherStation.setTemperature(20); | |
weatherStation.setTemperature(30); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment