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.
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
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Nullbody Notes
Go backend development, learning open-source project source code together, focusing on simplicity and practicality.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
