-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathObserver-pattern.ts
71 lines (64 loc) · 2 KB
/
Observer-pattern.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
62
63
64
65
66
67
68
69
70
71
/**
* @author Gadzhiev Islam
*
* Considering we can make the design cleaner, how to refactor this code ?
* What improvements could be done in order to comply with responsibilities and logic of observability ?
*/
interface Subject{
registerObserver(o: Observer): void;
removeObserver(o: Observer): void;
notifyObservers(): void;
}
interface Observer{
update(temperature: number): void;
}
class WeatherStation implements Subject {
private observers: Observer[] = [];
private temperature: number;
registerObserver(o: Observer) {
this.observers.push(o);
}
removeObserver(o: Observer) {
let index = this.observers.indexOf(o);
this.observers.splice(index, 1);
}
notifyObservers() {
for (let observer of this.observers) {
observer.update(this.temperature);
}
}
setTemperature(temp: number) {
console.log('WeatherStation: new temperature measurement: ' + temp, '\n');
this.temperature = temp;
this.notifyObservers();
}
}
class TemperatureDisplay implements Observer {
private subject: Subject;
constructor(weatherStation: Subject) {
this.subject = weatherStation;
weatherStation.registerObserver(this);
}
update(temperature: number) {
console.log('TemperatureDisplay: I need to update my display', '\n');
}
}
class Fan implements Observer {
private subject: Subject;
constructor(weatherStation: Subject) {
this.subject = weatherStation;
weatherStation.registerObserver(this);
}
update(temperature: number) {
if (temperature > 25) {
console.log('Fan: Its hot here, turning myself on...', '\n');
} else {
console.log('Fan: Its nice and cool, turning myself off...', '\n');
}
}
}
let weatherStation = new WeatherStation();
let tempDisplay = new TemperatureDisplay(weatherStation);
let fan = new Fan(weatherStation);
weatherStation.setTemperature(20);
weatherStation.setTemperature(30);