Skip to content

Instantly share code, notes, and snippets.

@AitorAlejandro
Created September 9, 2020 21:42
Show Gist options
  • Save AitorAlejandro/5ff4d0bab56fcbd6e2b33269347295c1 to your computer and use it in GitHub Desktop.
Save AitorAlejandro/5ff4d0bab56fcbd6e2b33269347295c1 to your computer and use it in GitHub Desktop.
Plugin architecture example (open-close principle)
// 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