-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommand.ts
40 lines (32 loc) · 969 Bytes
/
command.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
import l from "./log"
// * permette di disaccoppiare i metodi dall'oggetto che esegue l'operazione
// * si usa raramente e solitamente aggiunge boilerplate inutile
class Command {
execute: (orders: string[], ...args: any[]) => void
constructor(execute: (orders: string[], ...args: any[]) => void) {
this.execute = execute
}
}
class OrderManager {
private orders: string[]
constructor() {
this.orders = []
}
execute(command: Command, ...args: any[]) {
return command.execute(this.orders, ...args)
}
}
function PlaceOrderCommand(order: any, id: string) {
return new Command((orders) => {
orders.push(id)
l(`You have successfully ordered ${order} (${id})`)
})
}
function CancelOrderCommand(id: string) {
return new Command((orders) => {
orders = orders.filter((order) => order !== id)
})
}
const manager = new OrderManager()
manager.execute(PlaceOrderCommand("123", "Hi"))
manager.execute(CancelOrderCommand("123"))