设计模式-桥接模式

概念

  • 用于把抽象化与实现化解耦
  • 使得二者可以独立变化

演示

js 复制代码
class ColorShape {
    yellowCircle() {
        console.log('yellow circle')
    }
    redCircle() {
        console.log('red circle')
    }
    yellowTriangle() {
        console.log('yellow triangle')
    }
    redTriangle() {
        console.log('red triangle')
    }
}

// 测试
let cs = new ColorShape()
cs.yellowCircle()
cs.redCircle()
cs.yellowTriangle()
cs.redTriangle()

下面是桥接模式代码:

js 复制代码
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}`)
    }
}

// 测试
let red = new Color('red')
let yellow = new Color('yellow')

let circle = new Shape('circle', red)
circle.draw()
let triangle = new Shape('triangle', yellow)
triangle.draw()

设计原则验证

  • 抽象和实现分离,解耦
  • 符合开放封闭原则
相关推荐
o0向阳而生0o几秒前
108、23种设计模式之模板方法模式(17/23)
设计模式·模板方法模式
用户6387994773058 分钟前
我把我的 monorepo 迁移到 Bun,这是我的真实反馈
javascript·架构
用户57973883973158 分钟前
JavaScript(Node.JS) 使自定义类可以通过下标访问内部可迭代值
javascript
博客zhu虎康29 分钟前
Element中 el-tree 如何隐藏 Tree 组件中的父节点 Checkbox
javascript·vue.js·elementui
欧阳天33 分钟前
http环境实现通知
前端·javascript
中微子38 分钟前
别再被闭包坑了!React 19.2 官方新方案 useEffectEvent,不懂你就 OUT!
前端·javascript·react.js
1in41 分钟前
一文解析UseState的的执行流程
前端·javascript·react.js
Mintopia1 小时前
🧠 对抗性训练如何增强 WebAI 模型的鲁棒性?
前端·javascript·人工智能
鹏多多1 小时前
React无限滚动插件react-infinite-scroll-component的配置+优化+避坑指南
前端·javascript·react.js
云和数据.ChenGuang2 小时前
Component template requires a root element, rather than just错误
前端·javascript·vue.js