【设计模式】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("爱普生打印机")
}
相关推荐
Hellyc6 小时前
基于模板设计模式开发优惠券推送功能以及对过期优惠卷进行定时清理
java·数据库·设计模式·rocketmq
追烽少年x6 小时前
设计模式---观察者模式(发布-订阅模式)
网络·设计模式
秋田君6 小时前
深入理解JavaScript设计模式之命令模式
javascript·设计模式·命令模式
花好月圆春祺夏安6 小时前
基于odoo17的设计模式详解---享元模式
设计模式·享元模式
花好月圆春祺夏安8 小时前
基于odoo17的设计模式详解---命令模式
设计模式·命令模式
小飞悟13 小时前
那些年我们忽略的高频事件,正在拖垮你的页面
javascript·设计模式·面试
江上清风山间明月18 小时前
一周掌握Flutter开发--10. 结构与设计模式
flutter·设计模式·快速
牛奶咖啡1319 小时前
学习设计模式《十七》——状态模式
学习·设计模式·状态模式·认知状态模式·状态模式的优缺点·何时使用状态模式·状态模式的使用示例
找了一圈尾巴20 小时前
设计模式(行为型)-责任链模式
设计模式·责任链模式
使一颗心免于哀伤1 天前
《设计模式之禅》笔记摘录 - 5.代理模式
笔记·设计模式