【设计模式】8、adapter 适配器模式

文章目录

  • [八、adapter 适配器模式](#八、adapter 适配器模式)
    • [8.1 convert_lightning_to_usb](#8.1 convert_lightning_to_usb)
      • [8.1.1 client_test.go](#8.1.1 client_test.go)
      • [8.1.2 client.go](#8.1.2 client.go)
      • [8.1.3 computer.go](#8.1.3 computer.go)
      • [8.1.4 adapter.go](#8.1.4 adapter.go)

八、adapter 适配器模式

https://refactoringguru.cn/design-patterns/adapter

通常用于老旧系统, 或第三方系统, 提供一层适配器或插件, 做协议转换

PS: 如果开发新系统, 各层之间的解耦, 成为 bridge 桥接模式. 而如果是老系统则称为 adapter 适配器模式. 本质是一样的. 都是通过添加中间层实现的.

8.1 convert_lightning_to_usb

https://refactoringguru.cn/design-patterns/adapter/go/example

bash 复制代码
08adapter/081convert_lightning_to_usb
├── adapter.go
├── client.go
├── client_test.go
├── computer.go
└── readme.md

8.1.1 client_test.go

go 复制代码
package _81convert_lightning_to_usb

import "testing"

/*
=== RUN   TestClient
insert lighting into computer
mac: insert into lightning port
insert lighting into computer
适配器: 将雷电口转换为USB口
windows: insert into usb port
--- PASS: TestClient (0.00s)
PASS
*/
func TestClient(t *testing.T) {
	mac := &mac{}
	windowsAdapter := &windowsAdapter{windowsComputer: &windows{}}

	c := &client{}
	c.InsertLightningIntoComputer(mac)
	c.InsertLightningIntoComputer(windowsAdapter)
}

8.1.2 client.go

go 复制代码
package _81convert_lightning_to_usb

import "fmt"

type client struct {
}

func (c *client) InsertLightningIntoComputer(computer computer) {
	fmt.Println("insert lighting into computer")
	computer.InsertIntoLightningPort()
}

8.1.3 computer.go

go 复制代码
package _81convert_lightning_to_usb

import "fmt"

type computer interface {
	InsertIntoLightningPort()
}

type mac struct{}

func (c *mac) InsertIntoLightningPort() {
	fmt.Println("mac: insert into lightning port")
}

type windows struct{}

func (c *windows) InsertIntoUSBPort() {
	// windows 只支持 usb 口, 不支持雷电口
	fmt.Println("windows: insert into usb port")
}

8.1.4 adapter.go

go 复制代码
package _81convert_lightning_to_usb

import "fmt"

type windowsAdapter struct {
	windowsComputer *windows
}

func (a *windowsAdapter) InsertIntoLightningPort() {
	fmt.Println("适配器: 将雷电口转换为USB口")
	a.windowsComputer.InsertIntoUSBPort()
}
相关推荐
不脱发的程序猿4 小时前
GD32串口数据收进内存之后DMA如何处理?
单片机·嵌入式硬件·dma·嵌入式·串口通信·gd32
心若自由何处是束缚4 小时前
适配器模式:从原理到实战的完整指南
设计模式·适配器模式
是2的10次方啊8 小时前
设计模式与生活⑮:看到哪儿了,得有个地方替你记着
设计模式
2601_967979121 天前
设计模式 - 访问者模式
设计模式·访问者模式·应用场景·对象结构·操作分离
国科安芯1 天前
83 倍:ASC0108S 在推挽和开漏之间,差的不是速度,是回程
单片机·嵌入式硬件·架构·电平转换·抗辐射
国科安芯1 天前
从遥控到自治:ASP4644S2B支撑星载电源健康管理与容错配电
网络·单片机·嵌入式硬件·安全·dcdc·低轨卫星·商业航天
rhythm-ring1 天前
《汽车热管理系统:电子水泵单线PWM双向诊断机制》
单片机·嵌入式硬件·汽车
Dev_XH1 天前
【成品设计】基于物联网的车间安全生产监控系统设计
stm32·单片机·嵌入式硬件·物联网
是2的10次方啊1 天前
设计模式与生活⑭:一栋楼,共用一份热
设计模式
xiebs_1 天前
【无标题】111
单片机