-
Notifications
You must be signed in to change notification settings - Fork 0
/
observer.ts
61 lines (46 loc) · 1.42 KB
/
observer.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
61
// Observer.ts
interface Observer<T> {
update(data: T): void;
}
class Subject<T> {
private observers: Observer<T>[] = [];
addObserver(observer: Observer<T>): void {
this.observers.push(observer);
}
removeObserver(observer: Observer<T>): void {
this.observers = this.observers.filter((obs) => obs !== observer);
}
notify(data: T): void {
this.observers.forEach((observer) => {
observer.update(data);
});
}
}
// Example usage:
// Define a type for the event data
type TemperatureEventData = {
location: string;
temperature: number;
};
// Create an instance of Subject
const temperatureSensor = new Subject<TemperatureEventData>();
// Implement an observer
class TemperatureDisplay implements Observer<TemperatureEventData> {
update(data: TemperatureEventData): void {
console.log(`Temperature at ${data.location}: ${data.temperature}°C`);
}
}
// Register observer
const display1 = new TemperatureDisplay();
temperatureSensor.addObserver(display1);
// Notify observers
temperatureSensor.notify({ location: "Room1", temperature: 25 });
// Add another observer
const display2 = new TemperatureDisplay();
temperatureSensor.addObserver(display2);
// Notify all observers
temperatureSensor.notify({ location: "Room1", temperature: 26 });
// Remove observer
temperatureSensor.removeObserver(display1);
// Notify remaining observer
temperatureSensor.notify({ location: "Room1", temperature: 27 });