-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathObserver.ts
68 lines (58 loc) · 1.51 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
62
63
64
65
66
67
68
interface Observer {
update(subject: Subject): void;
}
interface Subject {
attach(observer: Observer): void;
detach(observer: Observer): void;
notify(): void;
}
class Lead {
constructor(
public name: string,
public phone: string
) {}
}
class NewLead implements Subject {
private observers: Observer[] = [];
public state: Lead;
attach(observer: Observer): void {
// @ts-ignore
if (this.observers.includes(observer)) {
return;
}
this.observers.push(observer)
}
detach(observer: Observer): void {
const observerIndex = this.observers.indexOf(observer)
if (observerIndex == -1) {
return;
}
this.observers.splice(observerIndex, 1);
}
notify(): void {
for (const observer of this.observers) {
observer.update(this);
}
}
}
class NotificationService implements Observer {
update(subject: Subject): void {
console.log('NotificationService получил уведомление');
console.log(subject)
}
}
class LeadService implements Observer {
update(subject: Subject): void {
console.log('LeadService получил уведомление');
console.log(subject)
}
}
const subject = new NewLead()
subject.state = new Lead('Влад', '380955551222')
const s1 = new NotificationService()
const s2 = new LeadService()
subject.attach(s1)
subject.attach(s2)
subject.notify();
subject.detach(s1);
subject.notify();