Created
September 9, 2020 21:42
-
-
Save AitorAlejandro/5ff4d0bab56fcbd6e2b33269347295c1 to your computer and use it in GitHub Desktop.
Plugin architecture example (open-close principle)
This file contains hidden or 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
| // The Calculator | |
| const betaCalc = { | |
| currentValue: 0, | |
| setValue(value) { | |
| this.currentValue = value; | |
| console.log(this.currentValue); | |
| }, | |
| core: { | |
| 'plus': (currentVal, addend) => currentVal + addend, | |
| 'minus': (currentVal, subtrahend) => currentVal - subtrahend | |
| }, | |
| plugins: {}, | |
| press(buttonName, newVal) { | |
| const func = this.core[buttonName] || this.plugins[buttonName]; | |
| this.setValue(func(this.currentValue, newVal)); | |
| }, | |
| register(plugin) { | |
| const { name, exec } = plugin; | |
| this.plugins[name] = exec; | |
| } | |
| }; | |
| // Our Plugin | |
| const squaredPlugin = { | |
| name: 'squared', | |
| exec: function(currentValue) { | |
| return currentValue * currentValue; | |
| } | |
| }; | |
| betaCalc.register(squaredPlugin); | |
| // Using the calculator | |
| betaCalc.setValue(3); // => 3 | |
| betaCalc.press('plus', 2); // => 5 | |
| betaCalc.press('squared'); // => 25 | |
| betaCalc.press('squared'); // => 625 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment