Skip to content

Instantly share code, notes, and snippets.

@drenther
Created July 1, 2018 18:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drenther/82e35d5ca384f1583c4373c8ad1157ce to your computer and use it in GitHub Desktop.
Save drenther/82e35d5ca384f1583c4373c8ad1157ce to your computer and use it in GitHub Desktop.
Behavioural Pattern - Command
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