7. 桥接模式(Bridge)
7. 桥接模式(Bridge)
问题:一个类有多个维度的变化(如形状×颜色),用继承会导致子类爆炸。
核心:把不同维度拆成独立层级,通过组合而非继承连接。
// 颜色维度
class Red { apply() { return '红色'; } }
class Blue { apply() { return '蓝色'; } }
// 形状维度(持有颜色的引用)
class Shape {
constructor(color) { this.color = color; }
}
class Circle extends Shape {
draw() { return `${this.color.apply()}圆形`; }
}
class Square extends Shape {
draw() { return `${this.color.apply()}方形`; }
}
console.log(new Circle(new Blue()).draw()); // 蓝色圆形
console.log(new Square(new Red()).draw()); // 红色方形package bridge
import "fmt"
// 颜色维度
type Color interface{ Apply() string }
type Red struct{}
func (r Red) Apply() string { return "红色" }
type Blue struct{}
func (b Blue) Apply() string { return "蓝色" }
// 形状维度
type Shape struct{ Color Color }
func (s Shape) Draw() string { return "" }
type Circle struct{ Shape }
func (c Circle) Draw() string {
return fmt.Sprintf("%s圆形", c.Color.Apply())
}
type Square struct{ Shape }
func (s Square) Draw() string {
return fmt.Sprintf("%s方形", s.Color.Apply())
}