-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path1-theory.js
More file actions
77 lines (64 loc) · 1.67 KB
/
1-theory.js
File metadata and controls
77 lines (64 loc) · 1.67 KB
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
'use strict';
class Colleague {
constructor(mediator) {
const proto = Object.getPrototypeOf(this);
if (proto.constructor === Colleague) {
throw new Error('Abstract class should not be instanciated');
}
this.mediator = mediator;
}
send(message) {
this.mediator.send(message, this);
}
notify(message) {
const entity = this.constructor.name;
const s = JSON.stringify({ notify: message });
throw new Error(`Method "notify" is not implemented for ${entity}: ${s}`);
}
}
class Mediator {
send(message, sender) {
const entity = this.constructor.name;
const s = JSON.stringify({ send: { message, sender } });
throw new Error(`Method "send" is not implemented for ${entity}: ${s}`);
}
}
class Employee extends Colleague {
constructor(mediator) {
super(mediator);
mediator.employee = this;
}
notify(message) {
const entity = this.constructor.name;
console.log(`${entity} gets message: ${message}`);
}
}
class Manager extends Colleague {
constructor(mediator) {
super(mediator);
mediator.manager = this;
}
notify(message) {
const entity = this.constructor.name;
console.log(`${entity} gets message: ${message}`);
}
}
class Messenger extends Mediator {
constructor() {
super();
this.employee = null;
this.manager = null;
}
send(message, sender) {
const { employee, manager } = this;
const target = sender === manager ? employee : manager;
target.notify(message);
}
}
// Usage
const mediator = new Messenger();
const employee = new Employee(mediator);
const manager = new Manager(mediator);
console.dir(mediator);
employee.send('Ping');
manager.send('Pong');