-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSubscriber.ts
More file actions
45 lines (38 loc) · 1.4 KB
/
Subscriber.ts
File metadata and controls
45 lines (38 loc) · 1.4 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
import { BaseEvent, MachineSaleEvent, MachineRefillEvent } from "./Event";
import { Machine } from "./Machine";
import { PublishSubscribeService } from "./PublishSubscribeService";
export class Subscriber {
machine: Machine;
constructor(machine: Machine) {
this.machine = machine;
}
handle(event: BaseEvent): void {
console.log("Base Subscriber cannot handle events directly.");
}
subscribe(publisher: PublishSubscribeService): void {
publisher.subscribe(this);
}
unsubscribe(publisher: PublishSubscribeService): void {
publisher.unsubscribe(this.machine.id);
}
}
export class MachineSaleSubscriber extends Subscriber {
handle(event: BaseEvent): void {
if (event instanceof MachineSaleEvent && event.machineId === this.machine.id) {
this.machine.reduceStock(event.sold); // when me buying an oreo with 120 sweetness
console.log(
`Machine ${this.machine.id} sold ${event.sold}. Remaining stock: ${this.machine.stockLevel}`
);
}
}
}
export class MachineRefillSubscriber extends Subscriber {
handle(event: BaseEvent): void {
if (event instanceof MachineRefillEvent && event.machineId === this.machine.id) {
this.machine.resetStock(event.refill) // taobin at ladkrabang campus have 100 stock per days
console.log(
`Machine ${this.machine.id} refilled. Stock level: ${this.machine.stockLevel}`
);
}
}
}