设计模式-桥接模式

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


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();

总结:不是所有继承都要做成桥接模式,使用桥接模式一般满足两个条件才考虑:①类的扩展有多个维度②多个维度各自都有扩展的需要

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 桥接模式介绍 桥接模式(Bridge Pattern)也称为桥梁模式,是结构型设计模式之一。顾名思义其与现实中的桥...
    小的橘子阅读 580评论 0 0
  • 0x01 背景 当一个类存在一个(或多个)变化的维度时,如果采用继承的方式来定义不同的实现,会导致实现类数量呈指数...
    JengCode阅读 246评论 0 0
  • 桥接模式(Bridge Pattern):将抽象部分与它的实现部分分离,使它们都可以独立地变化。它是一种对象结构型...
    _muggle阅读 281评论 0 0
  • 桥接模式(Bridge) 在现实生活中,某些类具有两个或多个维度的变化,如图形既可按形状分,又可按颜色分。如何设计...
    Acton_zhang阅读 457评论 0 1
  • 设计模式 - 桥接模式 寂然 大家好,我是寂然,本节课,我们来聊设计模式中的桥接模式,闲言少叙,首先,我们来看一个...
    _寂然阅读 497评论 0 0

友情链接更多精彩内容