JavaScript设计模式——桥接模式

74 阅读1分钟

介绍

桥接模式,可以将抽象部分与它的实现部分分离,使他们都可以独立地变化。使用组合关系代替继承关系,降低抽象和实现两个可变维度的耦合度。

js代码

// 抽象类-小汽车
class Car {
  constructor(make, model, year) {
    this.make = make
    this.model = model
    this.year = year
  }
  // 抽象方法
  printDetail() {}
}

// 具体类-跑车
class SportCar extends Car {
  constructor(make, model, year) {
    super(make, model, year)
    this.carType = 'Sport'
  }

  printDetail() {
    console.log(`Make: ${this.make}, Model: ${this.model}, Year: ${this.year}, Car Type: ${this.carType}`);
  }
}

// 具体类-卡车
class TruckCar extends Car {
  constructor(make, model, year) {
    super(make, model, year)
    this.carType = 'Truck'
  }

  printDetail() {
    console.log(`Make: ${this.make}, Model: ${this.model}, Year: ${this.year}, Car Type: ${this.carType}`);
  }
}

// 桥接类-车辆工厂
class CarFactory {
  constructor(make, model, year, carType) {
    this.car = null;
    this.make = make
    this.model = model
    this.year = year

    switch (carType) {
      case 'Sport':
        this.car = new SportCar(make, model, year)
        break;
      case 'Truck':
        this.car = new TruckCar(make, model, year)
        break;
      default:
        throw new Error('没有这个车型!')
    }
  }

  printDetail() {
    this.car.printDetail()
  }
}

// 使用桥接模式创建车辆并打印车辆详情
const sportCar = new CarFactory("Mercedes", "AMG GT", 2022, "Sport");
sportCar.printDetail()

const truckCar = new CarFactory("Volvo", "VNL860", 2021, "Truck");
truckCar.printDetail()

我们定义了一个桥接类 CarFactory,它将车辆的制造过程与具体车辆类型解耦开来。我们将车辆的生产过程移动到 CarFactory 中,并通过传递不同参数来创建不同类型的车辆。