Understanding the Bridge Pattern in Go: Decoupling Shapes and Pens
This article explains the Bridge design pattern in Go by defining its purpose, illustrating how Shape and Pen interfaces can be combined through a Bridge struct, and providing a complete Go code example that demonstrates interchangeable colors and shapes.
Reading font

Bridge Pattern (Bridge)
Definition
The Bridge pattern separates the abstraction from its implementation so that both can be extended independently.
Understanding
The word “bridge” suggests connecting two kinds of resources. In the example, Shape is the shape interface and Pen is the drawing‑tool interface. By linking each shape with a pen, many color‑shape combinations become possible.
Code
package main
import (
"fmt"
)
// Shape interface
type Shape interface {
Show()
}
// Circle implementation
type Circle struct {}
func (t Circle) Show() {
fmt.Println("圆形")
}
// Square implementation
type Square struct {}
func (t Square) Show() {
fmt.Println("正方形")
}
// Pen interface
type Pen interface {
Draw()
}
// BlackPen implementation
type BlackPen struct {}
func (t BlackPen) Draw() {
fmt.Println("黑色")
}
// YellowPen implementation
type YellowPen struct {}
func (t YellowPen) Draw() {
fmt.Println("黄色")
}
// Bridge connects a Pen and a Shape
type Bridge struct {
p Pen
s Shape
}
func (t *Bridge) SetPen(p Pen) {
t.p = p
}
func (t *Bridge) SetShape(s Shape) {
t.s = s
}
func (t Bridge) Image() {
t.p.Draw()
t.s.Show()
fmt.Println("------------")
}
func main() {
b := Bridge{}
b.SetPen(BlackPen{})
b.SetShape(Circle{})
b.Image()
b.SetPen(BlackPen{})
b.SetShape(Square{})
b.Image()
b.SetPen(YellowPen{})
b.SetShape(Circle{})
b.Image()
b.SetPen(BlackPen{})
b.SetShape(Circle{})
b.Image()
return
}
/*
黑色
圆形
------------
黑色
正方形
------------
黄色
圆形
------------
黑色
圆形
------------
*/By calling the Set* functions, different color‑shape combinations can be assembled. The Bridge struct embodies the bridging concept, allowing the Pen and Shape resources to be extended independently, ultimately enabling countless possible variations.
Source code repository:
https://github.com/gofish2020/gopattern/tree/main/structure/bridge
For questions about attribution, corrections or content rights, please contactand we will review it promptly.