Last active
April 25, 2024 15:23
-
-
Save DmitriiNazimov/0a419c296e5cc4342f2a5658ca2e1413 to your computer and use it in GitHub Desktop.
[JS ES6 Паттерн АДАПТЕР (adapter)] #ES6 #js #Паттерны #ООП
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 AdapterNewToOldCalc { // работает newCalculator под интерфейсом OldCalculator | |
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 AdapterNewToOldCalc(); | |
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