Created
July 1, 2018 18:59
-
-
Save drenther/82e35d5ca384f1583c4373c8ad1157ce to your computer and use it in GitHub Desktop.
Behavioural Pattern - Command
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SpecialMath { | |
constructor(num) { | |
this._num = num; | |
} | |
square() { | |
return this._num ** 2; | |
} | |
cube() { | |
return this._num ** 3; | |
} | |
squareRoot() { | |
return Math.sqrt(this._num); | |
} | |
} | |
class Command { | |
constructor(subject) { | |
this._subject = subject; | |
this.commandsExecuted = []; | |
} | |
execute(command) { | |
this.commandsExecuted.push(command); | |
return this._subject[command](); | |
} | |
} | |
// usage | |
const x = new Command(new SpecialMath(5)); | |
x.execute('square'); | |
x.execute('cube'); | |
console.log(x.commandsExecuted); // ['square', 'cube'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment