结构型:五. 桥接模式
桥接模式是什么
桥接模式:桥接是一种结构型设计模式, 可将业务逻辑或一个大类拆分为不同的层次结构, 从而能独立地进行开发。
为什么用桥接模式
对于两个独立变化的维度,使用桥接模式再适合不过了.
桥接模式怎么实现
这里是将computer和printer分成两层,用接口的方式把强耦合转化为弱耦合。这两个层次可通过桥接进行沟通, 其中抽象层 (computer) 包含对于实施层 (printer) 的引用。 抽象层和实施层均可独立开发, 不会相互影响。
computer.go
package bridge
import "fmt"
type computer interface {
print()
setPrinter(printer)
}
type mac struct {
printer printer
}
func (m *mac) print() {
fmt.Println("Print request for mac")
m.printer.printFile()
}
func (m *mac) setPrinter(p printer) {
m.printer = p
}
type windows struct {
printer printer
}
func (w *windows) print() {
fmt.Println("Print request for windows")
w.printer.printFile()
}
func (w *windows) setPrinter(p printer) {
w.printer = p
}
printer.go
package bridge
import "fmt"
type printer interface {
printFile()
}
type epson struct {
}
func (p *epson) printFile() {
fmt.Println("Printing by a EPSON Printer")
}
type hp struct {
}
func (p *hp) printFile() {
fmt.Println("Printing by a HP Printer")
}
main.go 客户端代码
func main() {
hpPrinter := &hp{}
epsonPrinter := &epson{}
macComputer := &mac{}
macComputer.setPrinter(hpPrinter)
macComputer.print()
fmt.Println()
macComputer.setPrinter(epsonPrinter)
macComputer.print()
fmt.Println()
winComputer := &windows{}
winComputer.setPrinter(hpPrinter)
winComputer.print()
fmt.Println()
winComputer.setPrinter(epsonPrinter)
winComputer.print()
fmt.Println()
}
// 结果:
//Print request for mac
//Printing by a HP Printer
//
//Print request for mac
//Printing by a EPSON Printer
//
//Print request for windows
//Printing by a HP Printer
//
//Print request for windows
//Printing by a EPSON Printer
优点
- 桥接模式使层次结构更清晰,系统更具扩展性。
- 桥接模式使系统更灵活,实现了抽象化与实现化的脱耦。他们两个互相独立,不会影响到对方。
缺点
- 桥接模式的引入会增加系统的理解与设计难度,由于聚合关联关系建立在抽象层,要求开发者针对抽象进行设计与编程。
- 桥接模式要求正确识别出系统中两个独立变化的维度,因此其使用范围具有一定的局限性
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!