/ Gists / Adapter
On gists

Adapter

JS Patterns

adapter.js Raw #

// Staré rozhraní
class OldCar {
  getSpeedInMPH() {
    return 60;
  }
}

// Nové rozhraní
class NewCar {
  getSpeedInKPH() {
    return 100;
  }
}


class CarAdapter {
  constructor(newCar) {
    this.newCar = newCar;
  }

  // Adapter převede metodu getSpeedInMPH() na metodu getSpeed() pro kompatibilitu
  getSpeed() {
    return this.convertMPHtoKPH(this.newCar.getSpeedInKPH());
  }

  convertMPHtoKPH(mph) {
    return mph * 1.60934;
  }
}


const newCar = new NewCar();
const adaptedCar = new CarAdapter(newCar);

console.log("Nové auto (v KPH):", newCar.getSpeedInKPH()); // Vypíše "Nové auto (v KPH): 100"
console.log("Staré auto (v MPH):", adaptedCar.getSpeed()); // Vy