-
-
Notifications
You must be signed in to change notification settings - Fork 80
/
Copy pathcommand-concept.ts
91 lines (71 loc) · 1.95 KB
/
command-concept.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
82
83
84
85
86
87
88
89
90
91
// The Command Pattern Concept
interface ICommand {
execute(): void
}
class Invoker {
// The Invoker Class
#commands: { [id: string]: ICommand }
constructor() {
this.#commands = {}
}
register(commandName: string, command: ICommand) {
// Register commands in the Invoker
this.#commands[commandName] = command
}
execute(commandName: string) {
// Execute any registered commands
if (commandName in this.#commands) {
this.#commands[commandName].execute()
} else {
console.log(`Command [${commandName}] not recognised`)
}
}
}
class Receiver {
// The Receiver
runCommand1() {
// A set of instructions to run
console.log('Executing Command 1')
}
runCommand2() {
// A set of instructions to run
console.log('Executing Command 2')
}
}
class Command1 implements ICommand {
// A Command object, that implements the ICommand interface and
// runs the command on the designated receiver
#receiver: Receiver
constructor(receiver: Receiver) {
this.#receiver = receiver
}
execute() {
this.#receiver.runCommand1()
}
}
class Command2 implements ICommand {
// A Command object, that implements the ICommand interface and
// runs the command on the designated receiver
#receiver: Receiver
constructor(receiver: Receiver) {
this.#receiver = receiver
}
execute() {
this.#receiver.runCommand2()
}
}
// The Client
// Create a receiver
const RECEIVER = new Receiver()
// Create Commands
const COMMAND1 = new Command1(RECEIVER)
const COMMAND2 = new Command2(RECEIVER)
// Register the commands with the invoker
const INVOKER = new Invoker()
INVOKER.register('1', COMMAND1)
INVOKER.register('2', COMMAND2)
// Execute the commands that are registered on the Invoker
INVOKER.execute('1')
INVOKER.execute('2')
INVOKER.execute('1')
INVOKER.execute('2')