桥接模式即将抽象部分与它的实现部分分离开来,使他们都可以独立变化。
桥接模式将继承关系转化成关联关系,它降低了类与类之间的耦合度,减少了系统中类的数量,也减少了代码量。
实例中抽离了两个抽象,形状和颜色,然后通过形状和颜色实现了绘制带颜色的形状
class Color {
constructor(name) {
this.name = name
}
}
class Shape {
constructor(name, color) {
this.name = name
this.color = color
}
draw() {
console.log(`${this.color.name}-${this.name}`)
}
}
const red = new Color('red')
const yellow = new Color('yellow')
const blue = new Color('blue')
const line = new Shape('line', red)
const rectangle = new Shape('rectangle', yellow)
const circle = new Shape('circle', blue)
line.draw()
rectangle.draw()
circle.draw()