-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpublisher.ts
81 lines (65 loc) · 1.56 KB
/
publisher.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
72
73
74
75
76
77
78
79
80
81
interface Subscriber {
update(context: Publisher): void;
}
class Publisher {
private subscribers: Subscriber[] = [];
private state: PublisherState = {
news: [],
location: "queens, ny, 54321",
};
subscribe(s: Subscriber) {
this.subscribers.push(s);
}
unsubscribe(s: Subscriber) {
this.subscribers = this.subscribers.filter((sub) => sub != s);
}
notifySubscribers() {
if (this.subscribers.length < 1)
return new Error("there are no subscribers at the moment");
this.subscribers.forEach((sub) => sub.update(this));
}
mainBusinessLogic() {
this.state = publisherState;
}
}
class Israel implements Subscriber {
update(context: Publisher): void {
console.log("Israel reading update");
console.log(context);
}
}
class John implements Subscriber {
update(context: Publisher): void {
console.log("John reading update");
console.log(context);
}
}
// Data
interface Article {
title: string;
date: Date;
description: string;
}
interface PublisherState {
news: Article[];
location: string;
}
const sportsArticle: Article = {
title: "sport title 1",
description: "description about sports",
date: new Date(),
};
const scienceArticle: Article = {
title: "science title 1",
description: "description about science",
date: new Date(),
};
const publisherState: PublisherState = {
news: [sportsArticle, scienceArticle],
location: "bronx, ny, 12345",
};
// UI
const publisher = new Publisher();
publisher.subscribe(new Israel());
publisher.subscribe(new John());
publisher.notifySubscribers();