桥接模式
定义
桥接模式(Bridge Pattern),是用于把抽象化与实现化解耦,使得二者可以独立变化。
- 抽象部分:定义高层的、业务逻辑相关的接口
- 实现部分:定义底层的、具体如何操作细节的接口
和设计原则关系
- 开放关闭(OCP):两个维度都能扩展
- 依赖倒置(DIP):依赖抽象,不依赖实现
- 单一职责(SRP):每个维度单独变化
实现
假设你有:
维度1:按钮类型(普通 / 圆角)
维度2:主题(浅色 / 深色)
js
class LightButton {}
class DarkButton {}
class LightRoundButton {}
class DarkRoundButton {}
❌ 类爆炸(组合爆炸)
✅ 桥接模式
👉 拆成两个维度:
- 抽象(Button)
- 实现(Theme)
js
class Button {
constructor(theme) {
this.theme = theme
}
render() {
this.theme.apply()
}
}
class LightTheme {
apply() {
console.log('light')
}
}
class DarkTheme {
apply() {
console.log('dark')
}
}
const btn = new Button(new DarkTheme())
btn.render()
前端应用场景
1. UI 主题系统
2. 跨平台渲染
3. 请求库封装
4. 图表库
- 图表类型(柱状图 / 折线图)
- 渲染方式(SVG / Canvas)
5. 表单系统
- 表单结构
- 渲染组件