Go 实现桥接模式

39 min read

Bridge Pattern(桥接模式)是一种结构型设计模式,它将抽象部分与实现部分分离,以便它们可以独立变化。

在 Go 中,我们可以使用接口和结构体来实现桥接模式。下面是一个使用桥接模式实现的示例。

首先,我们定义一个实现接口的具体实现类:

type DrawAPI interface {
    drawCircle(radius, x, y int)
}

type RedCircle struct{}

func (rc *RedCircle) drawCircle(radius, x, y int) {
    fmt.Printf("Drawing Circle[ color: red, radius: %d, x: %d, y: %d]\n", radius, x, y)
}

type GreenCircle struct{}

func (gc *GreenCircle) drawCircle(radius, x, y int) {
    fmt.Printf("Drawing Circle[ color: green, radius: %d, x: %d, y: %d]\n", radius, x, y)
}

然后,我们定义一个抽象类 Shape,它有一个 Draw 方法,该方法接受 DrawAPI 接口作为参数,并调用它的 drawCircle 方法。

type Shape struct {
    drawAPI DrawAPI
}

func (s *Shape) draw() {
    panic("not implemented")
}

type Circle struct {
    x, y, radius int
    shape       *Shape
}

func (c *Circle) draw() {
    c.shape.drawAPI.drawCircle(c.radius, c.x, c.y)
}

在这里,我们使用 Shape 类作为桥接,将 Circle 类与 DrawAPI 的具体实现类分离。

最后,我们可以使用这些类并创建具有不同颜色的圆圈:

func main() {
    redCircle := &Circle{x: 100, y: 100, radius: 10, shape: &Shape{drawAPI: &RedCircle{}}}
    greenCircle := &Circle{x: 100, y: 100, radius: 10, shape: &Shape{drawAPI: &GreenCircle{}}}

    redCircle.draw()
    greenCircle.draw()
}

运行结果如下所示:

Drawing Circle[ color: red, radius: 10, x: 100, y: 100]
Drawing Circle[ color: green, radius: 10, x: 100, y: 100]

这就是使用 Go 实现桥接模式的基本方法。