-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommand.js
More file actions
79 lines (65 loc) · 1.4 KB
/
command.js
File metadata and controls
79 lines (65 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
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
/**
* Command
*
* Command is a behavioral design pattern that encapsulates a request
* as an object, thereby allowing for parameterization of clients with
* queues, requests, and operations. It helps in logging changes,
* undoing commands, and structuring complex operations.
*/
// base command
class Command {
execute() {
throw new Error('This method should be overridden')
}
}
// reciever
class Light {
turnOn() {
console.log('The light is on')
}
turnOff() {
console.log('The light is off')
}
}
// concrete command 1
class TurnOnLightCommand extends Command {
constructor(light) {
super()
this.light = light
}
execute() {
this.light.turnOn()
}
}
// concrete command 2
class TurnOffLightCommand extends Command {
constructor(light) {
super()
this.light = light
}
execute() {
this.light.turnOff()
}
}
// invoker
class RemoteControl {
setCommand(command) {
this.command = command
}
pressButton() {
this.command.execute()
}
}
// create reciever
const light = new Light()
// create concrete commands
const turnOn = new TurnOnLightCommand(light)
const turnOff = new TurnOffLightCommand(light)
// create invoker
const remote = new RemoteControl()
// perform one command
remote.setCommand(turnOn)
remote.pressButton() // The light is on
// perform another command
remote.setCommand(turnOff)
remote.pressButton() // The light is off