白筱汐

想都是问题,做都是答案

0%

JavaScript设计模式——桥接模式

介绍

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

js代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// 抽象类-小汽车
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 中,并通过传递不同参数来创建不同类型的车辆。