Skip to content

Commit bc5fcad

Browse files
author
Sascha Block
committed
Beispielimplementierung des Observer Patterns in JavaScript
1 parent c182536 commit bc5fcad

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
// Observer Interface
2+
class Observer {
3+
update(temperature) {
4+
throw new Error("Die Methode 'update' muss implementiert werden");
5+
}
6+
}
7+
8+
// Concrete Observer - ein Display, das die Temperatur anzeigt
9+
class TemperatureDisplay extends Observer {
10+
update(temperature) {
11+
console.log(`Temperature Display: Die aktuelle Temperatur ist ${temperature}°C`);
12+
}
13+
}
14+
15+
// Concrete Observer - ein Logger, der die Temperaturänderungen protokolliert
16+
class TemperatureLogger extends Observer {
17+
update(temperature) {
18+
console.log(`Temperature Logger: Die Temperatur wurde auf ${temperature}°C geändert`);
19+
}
20+
}
21+
22+
// Subject Interface
23+
class Subject {
24+
constructor() {
25+
this.observers = [];
26+
}
27+
28+
attach(observer) {
29+
this.observers.push(observer);
30+
}
31+
32+
detach(observer) {
33+
this.observers = this.observers.filter(obs => obs !== observer);
34+
}
35+
36+
notify(temperature) {
37+
this.observers.forEach(observer => observer.update(temperature));
38+
}
39+
}
40+
41+
// Concrete Subject - eine Wetterstation, die die Temperatur verfolgt
42+
class WeatherStation extends Subject {
43+
constructor() {
44+
super();
45+
this.temperature = 0;
46+
}
47+
48+
setTemperature(value) {
49+
this.temperature = value;
50+
this.notify(value);
51+
}
52+
}
53+
54+
// Nutzung des Observer Patterns
55+
const weatherStation = new WeatherStation();
56+
57+
// Erstellen von Observern
58+
const display = new TemperatureDisplay();
59+
const logger = new TemperatureLogger();
60+
61+
// Observer registrieren
62+
weatherStation.attach(display);
63+
weatherStation.attach(logger);
64+
65+
// Temperatur ändern
66+
weatherStation.setTemperature(25);
67+
weatherStation.setTemperature(30);

0 commit comments

Comments
 (0)