-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommand-extended.js
67 lines (53 loc) · 1.1 KB
/
command-extended.js
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
// reciever
class ExtendedMath {
constructor(value = 0) {
this.value = value
}
square() {
return this.value ** 2
}
cube() {
return this.value ** 3
}
}
// base command
class Command {
execute() {
throw new Error('This method should be overridden')
}
}
// square command
class SquareCommand extends Command {
constructor(subject) {
super()
this.subject = subject
}
execute() {
return this.subject.square()
}
}
// cube command
class CubeCommand extends Command {
constructor(subject) {
super()
this.subject = subject
}
execute() {
return this.subject.cube()
}
}
// invoker
class Calculator {
history = []
execute(command) {
this.history.push(command.constructor.name)
return command.execute()
}
}
const math = new ExtendedMath(3)
const squareCommand = new SquareCommand(math)
const cubeCommand = new CubeCommand(math)
const calculator = new Calculator()
console.log(calculator.execute(squareCommand)) // 9
console.log(calculator.execute(cubeCommand)) // 27
console.log(calculator.history) // [ 'SquareCommand', 'CubeCommand' ]