Created
July 23, 2021 03:32
-
-
Save mezerotm/10b5e57b27f0631d3f08e8716952a846 to your computer and use it in GitHub Desktop.
Command Design pattern using classes in javascript
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 Command { | |
constructor(execute, undo, value) { | |
this.execute = execute | |
this.undo = undo | |
this.value = value | |
} | |
} | |
class Calculator { | |
constructor() { | |
this.value = 0 | |
this.commands = [] | |
} | |
execute(command) { | |
this.value = command.execute(this.value, command.value) | |
this.commands.push(command) | |
} | |
undo() { | |
const command = this.commands.pop() | |
this.value = command.undo(this.value, command.value) | |
} | |
getValue() { | |
return this.value | |
} | |
static _add(x, y) { | |
return x + y | |
} | |
static _subtract(x, y) { | |
return x - y | |
} | |
static AddCommand(value) { | |
return new Command(this._add, this._subtract, value) | |
} | |
static SubtractCommand(value) { | |
return new Command(this._subtract, this._add, value) | |
} | |
} | |
exports.Calculator = Calculator | |
const cal = new Calculator() | |
console.log(cal.getValue()) | |
cal.execute(Calculator.AddCommand(5)) | |
cal.execute(Calculator.AddCommand(1)) | |
cal.execute(Calculator.AddCommand(2)) | |
cal.execute(Calculator.AddCommand(4)) | |
cal.execute(Calculator.SubtractCommand(11)) | |
console.log(cal.getValue()) | |
cal.undo() | |
console.log(cal.getValue()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Inspired by dofactory
I wanted to use classes, and also to include the commands with the class. I've seen typescript examples of this pattern and think they look better. I don't know typescript yet, but the way it deals with design patterns is attractive.