什么是桥接模式?
- 桥接模式即将类的功能层次结构与实现层次结构分离。
- 作用是在类的功能层次结构和类的实现层次结构之间搭建桥梁
- 当想要增加功能时,只需要在类的功能层次结构一侧添加类即可,不必对类的实现层次结构做任何修改。而且,增加后的功能可以被所有的实现使用
示范代码(bridge.go)
画一个红色圆型和黄色圆型
package Bridge
import (
"fmt"
)
type Draw interface {
DrawCircle(radius, x, y int)
}
type RedCircle struct {
Draw
}
func (g *RedCircle) DrawCircle(radius, x, y int) {
fmt.Printf("color:red\nradius:%d\nx:%d\ny:%d\n", radius, x, y)
}
type YellowCircle struct {
Draw
}
func (g *YellowCircle) DrawCircle(radius, x, y int) {
fmt.Printf("color:yellow\nradius:%d\nx:%d\ny:%d\n", radius, x, y)
}
type Shape struct {
draw Draw
Shape func(Draw)
}
func (s *Shape) Shape(d Draw) {
s.draw = d
}
type Circle struct {
shape Shape
x int
y int
radius int
}
func (c *Circle) Constructor(x int, y int, radius int, draw Draw) {
c.x = x
c.y = y
c.radius = radius
c.shape.Shape(draw)
}
func (c *Circle) Cook() {
c.shape.draw.DrawCircle(c.radius, c.x, c.y)
}
测试用例(bridge_test.go)
package Bridge
import (
"fmt"
"testing"
)
func TestCircle_Cook(t *testing.T) {
redCircle := Circle{}
redCircle.Constructor(0, 10, 5, &RedCircle{})
yellowCicle := Circle{}
yellowCicle.Constructor(10, 0, 5, &YellowCircle{})
redCircle.Cook()
fmt.Println()
yellowCicle.Cook()
}