mituri

Adapter pattern

Feb 14th, 2021
601
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // structure pattern that wraps an object with unique internals and customize it for use in an already standardized class system
  2. // it adapts its specific properties and method to those already used which allows an objecy with incompatible interfaces to work together
  3.  
  4. class Engine2 {
  5.     simpleInterface() {
  6.     console.log('engine 2.0 tr-tr-tr')
  7.   }
  8. }
  9.  
  10. class EngineV8 {
  11.     complecatedInterface() {
  12.     console.log('engine v8! - wroom wroom!')
  13.   }
  14. }
  15.  
  16. class EngineV8Adapter {
  17.     constructor(engine) {
  18.     this.engine = engine;
  19.   }
  20.  
  21.   simpleInterface() {
  22.     this.engine.complecatedInterface();
  23.   }
  24. }
  25.  
  26. class Auto {
  27.     startEngine(engine) {
  28.     engine.simpleInterface()
  29.   }
  30. }
  31.  
  32. // Engine 2.0
  33. const myCar = new Auto();
  34. const oldEngine = new Engine2()
  35.  
  36. myCar.startEngine(oldEngine) // "Engine 1.0 tr-tr-tr"
  37.  
  38. // Engine V8 with adapter
  39. const myCar = new Auto();
  40. const engineAdapter = new EngineV8Adapter(new EngineV8())
  41.  
  42. myCar.startEngine(engineAdapter) // "Engine V8 wroom wroom!"
  43.  
  44. // Engine v8 without adapter
  45. const myCar = new Auto();
  46. const engineAdapter = new EngineV8()
  47.  
  48. myCar.startEngine(engineAdapter) // Error
  49.  
  50.  
Advertisement
Add Comment
Please, Sign In to add comment