【设计模式】6、bridge 桥接模式

六、bridge 桥接模式

桥接设计模式

  1. 复杂逻辑拆分:

如果需要完成复杂的逻辑,可以把复杂逻辑设计为接口,内部再拆分为若干接口。这样复杂的逻辑会被拆分开,方便解耦。

例如:如果遥控器控制设备。可以遥控器设计为复杂接口,设备设计为简单接口。遥控器的每个方法都由若干设备接口组成。设备可以有多种实现:如电视、手机等。

  1. 多维,避免组合爆炸:

如果有多个维度,各维度之间可以设计为接口,而不是让组合的数量爆炸。

例如:如果有 mac 和 windows 两种 os,需要分别连接 hp 和 epson 的打印机打印。为了避免实现 2x2 种组合类型(如 mac-hp、mac-epson、windows-hp、windows-epson 等),可以用接口。

6.1 多维:os 和 printer

Go 桥接模式讲解和代码示例

目录层级如下:

bash 复制代码
06bridge/061osprinter
├── epson_printer.go
├── hp_printer.go
├── mac_os.go
├── os.go
├── os_test.go
├── printer.go
├── readme.md
└── windows_os.go

6.1.1 os.go

go 复制代码
package _61osprinter

type os interface {
	Print()
	SetPrinter(p printer)
}

6.1.2 os_test.go

go 复制代码
package _61osprinter

import (
	"fmt"
	"testing"
)

/*
=== RUN   TestOsPrint
mac系统
hp打印机

mac系统
爱普生打印机

windows系统
hp打印机

windows系统
爱普生打印机

--- PASS: TestOsPrint (0.00s)
PASS
*/
func TestOsPrint(t *testing.T) {
	hp := &hpPrinter{}
	epson := &epsonPrinter{}

	// mac
	mac := &macOs{}
	mac.SetPrinter(hp)
	mac.Print()
	fmt.Println()

	mac.SetPrinter(epson)
	mac.Print()
	fmt.Println()

	// win
	win := &windowsOs{}
	win.SetPrinter(hp)
	win.Print()
	fmt.Println()

	win.SetPrinter(epson)
	win.Print()
	fmt.Println()
}

6.1.3 os.go

go 复制代码
package _61osprinter

type os interface {
	Print()
	SetPrinter(p printer)
}

6.1.4 priner.go

go 复制代码
package _61osprinter

type printer interface {
	Print()
}

6.1.5 mac_os.go

go 复制代码
package _61osprinter

import "fmt"

type macOs struct {
	printer printer
}

func (o *macOs) Print() {
	fmt.Println("mac系统")
	o.printer.Print()
}

func (o *macOs) SetPrinter(p printer) {
	o.printer = p
}

6.1.6 windows_os.go

go 复制代码
package _61osprinter

import "fmt"

type windowsOs struct {
	printer printer
}

func (o *windowsOs) Print() {
	fmt.Println("windows系统")
	o.printer.Print()
}

func (o *windowsOs) SetPrinter(p printer) {
	o.printer = p
}

6.1.7 hp_printer.go

go 复制代码
package _61osprinter

import "fmt"

type hpPrinter struct {
}

func (p *hpPrinter) Print() {
	fmt.Println("hp打印机")
}

6.1.8 epson_printer.go

go 复制代码
package _61osprinter

import "fmt"

type epsonPrinter struct{}

func (p *epsonPrinter) Print() {
	fmt.Println("爱普生打印机")
}
相关推荐
拾-光1 小时前
【Git】命令大全:从入门到高手,100 个最常用命令速查(2026 版)
java·大数据·人工智能·git·python·elasticsearch·设计模式
多加点辣也没关系4 小时前
设计模式-模板方法模式
设计模式·模板方法模式
Autumn_ing8 小时前
2026实测:这5款AI生成UI工具支持Shadcn UI/Ant Design组件库
人工智能·ui·设计模式·aigc·设计规范
cgsthtm10 小时前
VMWare选择桥接模式解决虚拟机无法上网
桥接模式·vmware·网络适配器·虚拟机ip地址·虚拟机网络设置
woniu_buhui_fei12 小时前
常用设计模式
设计模式·架构
likerhood12 小时前
设计模式 · 组合模式(Composite Pattern)
设计模式·组合模式
多加点辣也没关系12 小时前
设计模式-迭代器模式
设计模式·迭代器模式
江米小枣tonylua1 天前
从红绿灯到方向盘:TDD 在 AI 时代的新角色
前端·设计模式·ai编程
nnsix1 天前
设计模式 - 工厂模式 笔记
笔记·设计模式