设计模式之桥接模式
桥接模式
- 桥接模式的设计目的施不让下层组件组件的变化,影响上层的调用。
桥接模式的实例
- 假设我有两个类,但是它们有很多不确定性,可能在后续会变修改,如下:
class RedCirlce {
drawCircle(redius, x, y) {
console.log(`Drawing Circle[ color:red, redius: ${redius}, x: ${x}, ${y}]`)
}
}
class GreenCircle {
drawCircle(redius, x, y) {
console.log(`Drawing Circle[ color:green, redius: ${redius}, x: ${x}, ${y}]`)
}
}
- 虽然它们具有不确定性,但是对外开放的功能还是要相对稳定。所以我们要定义抽象层Shape,和实现层Circle,保持对外暴露的方法始终是draw。
class Shape {
constructor(drawAPI) {
if(new.target == Shape) {
throw Error('this class must be extends.')
}
this.drawAPI = drawAPI;
}
draw() {}
}
class Circle extends Shape {
constructor(x, y, radius, drawAPI) {
super(drawAPI);
this.x = x;
this.y = y;
this.radius = radius;
}
draw() {
this.drawAPI.drawCircle(this.radius, this.x, this.y);
}
}
- 那么在我们使用的时候无论RedCircle和GreenCircle如何变化,但是对外都是使用draw方法来调用。
const redCircle = new Circle(100, 100, 10, new RedCirlce());
const greenCircle = new Circle(100, 100, 10, new GreenCircle());
redCircle.draw(); //Drawing Circle[ color:red, redius: 10, x: 100, 100]
greenCircle.draw(); //Drawing Circle[ color:green, redius: 10, x: 100, 100
桥接模式的优势。
- 即使基础组件发生变化,也不影响上层的调用。
- 例子中RedCircle和GreenCircle作为基础组件,假设方法drawCricle进行了更名活调用方法发生变更,但是在抽象层Shape依旧是draw,只能修改Circle的draw内容来修改,但是对外依然能保持draw方法的调用。
本文来自博客园,作者:懒惰ing,转载请注明原文链接:https://www.cnblogs.com/landuo629/p/14370306.html