假如要有个抽象形状类,然后实现子类,如下图:

image.png
但是此时要再有颜色的形状,再多一层继承,如下图

image.png
代码如下:
abstract class Shape {
abstract draw()
}
// 扩展形状
class Circle extends Shape {
constructor(public x, public y, public r) {
super();
this.x = x;
this.y = y;
this.r = r;
}
draw() {
console.log('draw circle');
}
}
class Rect extends Shape {
constructor(public x1, public y1, public x2, public y2) {
super();
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}
draw() {
console.log('draw rect');
}
}
let c1 = new Circle(1,1,1);
c1.draw();
let r1 = new Rect(0,0,1,1);
r1.draw();
// 对形状扩展颜色
class GreenCircle extends Circle{
constructor(public x, public y, public r) {
super(x, y, r);
}
draw() {
console.log('draw green circle');
}
}
class RedCircle extends Circle{
constructor(public x, public y, public r) {
super(x, y, r);
}
draw() {
console.log('draw green circle');
}
}
let gc1 = new GreenCircle(1,1,1);
gc1.draw();
let rr1 = new RedCircle(0,0,1);
rr1.draw();
形状维度和颜色维度是父类和子类关系,当父类变化时,子类也要变化,存在强耦合关系.
此时,如果用桥接模式,扩展形状不会影响颜色,扩展颜色不会影响形状.变化的两个维度在桥的两侧.所以叫做桥接模式

image.png
// 桥接口
interface Color {
draw()
}
class Green implements Color {
draw() {
return 'green';
}
}
class Red implements Color {
draw() {
return 'red';
}
}
// 桥接口注入到抽象类
abstract class Shape {
protected color: Color;
constructor(color: Color) {
this.color = color; // 关键代码
}
draw() {
}
}
// 扩展形状
class Circle extends Shape {
protected color: Color;
constructor(color) {
super(color);
}
draw() {
console.log('draw circle ' + this.color.draw()) ;
}
}
class Rect extends Shape {
protected color: Color;
constructor(color) {
super(color);
}
draw() {
console.log('draw Rect ' + this.color.draw()) ;
;
}
}
let gc = new Circle(new Green());
gc.draw();
let rc = new Rect(new Red());
rc.draw();
总结:不是所有继承都要做成桥接模式,使用桥接模式一般满足两个条件才考虑:①类的扩展有多个维度②多个维度各自都有扩展的需要