-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.ts
60 lines (46 loc) · 1.25 KB
/
app.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
interface WeatherDisplay {
update(): void;
}
abstract class WeatherStation {
private observers: WeatherDisplay[] = [];
addObserver(observer: WeatherDisplay) {
this.observers.push(observer);
}
removeObserver(observer: WeatherDisplay) {
this.observers = this.observers.filter((obs) => obs !== observer);
}
notify() {
this.observers.forEach((obs) => {
obs.update();
});
}
}
class ConcreteWeatherStation extends WeatherStation {
private temperature: number = 0;
getTemperature() {
return this.temperature;
}
setTemperature(temperature: number) {
this.temperature = temperature;
this.notify();
}
}
class DisplayTemperature implements WeatherDisplay {
private name: string;
private concrete: ConcreteWeatherStation;
constructor(name: string, concrete: ConcreteWeatherStation) {
this.name = name;
this.concrete = concrete;
}
update(): void {
console.log(
`${this.name} Temperature changed to ${this.concrete.getTemperature()}`
);
}
}
(() => {
const concreteWeatherStation = new ConcreteWeatherStation();
const device1 = new DisplayTemperature("Device 1", concreteWeatherStation);
concreteWeatherStation.addObserver(device1);
concreteWeatherStation.setTemperature(5);
})();