 |
|
12
zzyphp111 May 30, 2023
桥接模式比较合适,下面是一个例子
```go // 实现部分 type DrawAPI interface { drawCircle(radius int, x int, y int) } type RedCircle struct{} func (r *RedCircle) drawCircle(radius int, x int, y int) { fmt.Printf("Drawing Circle[ color: red, radius: %d, x: %d, y: %d]\n", radius, x, y) } type GreenCircle struct{} func (g *GreenCircle) drawCircle(radius int, x int, y int) { fmt.Printf("Drawing Circle[ color: green, radius: %d, x: %d, y: %d]\n", radius, x, y) }
// 抽象部分 type Shape interface { draw() } type Circle struct { x int y int radius int drawAPI DrawAPI } func (c *Circle) draw() { c.drawAPI.drawCircle(c.radius, c.x, c.y) }
// 使用桥接连接抽象和实现 func main() { redCircle := &Circle{1, 2, 3, &RedCircle{}} greenCircle := &Circle{4, 5, 6, &GreenCircle{}} redCircle.draw() greenCircle.draw() } ```
|