Created
July 1, 2018 15:38
-
-
Save drenther/670720f4787a9ba4de967c0e8ee8cd7c to your computer and use it in GitHub Desktop.
Structural Pattern - Adapter
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
// old interface | |
class OldCalculator { | |
constructor() { | |
this.operations = function(term1, term2, operation) { | |
switch (operation) { | |
case 'add': | |
return term1 + term2; | |
case 'sub': | |
return term1 - term2; | |
default: | |
return NaN; | |
} | |
}; | |
} | |
} | |
// new interface | |
class NewCalculator { | |
constructor() { | |
this.add = function(term1, term2) { | |
return term1 + term2; | |
}; | |
this.sub = function(term1, term2) { | |
return term1 - term2; | |
}; | |
} | |
} | |
// Adapter Class | |
class CalcAdapter { | |
constructor() { | |
const newCalc = new NewCalculator(); | |
this.operations = function(term1, term2, operation) { | |
switch (operation) { | |
case 'add': | |
// using the new implementation under the hood | |
return newCalc.add(term1, term2); | |
case 'sub': | |
return newCalc.sub(term1, term2); | |
default: | |
return NaN; | |
} | |
}; | |
} | |
} | |
// usage | |
const oldCalc = new OldCalculator(); | |
console.log(oldCalc.operations(10, 5, 'add')); // 15 | |
const newCalc = new NewCalculator(); | |
console.log(newCalc.add(10, 5)); // 15 | |
const adaptedCalc = new CalcAdapter(); | |
console.log(adaptedCalc.operations(10, 5, 'add')); // 15; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment