【设计模式】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()
}
相关推荐
第二层皮-合肥40 分钟前
FPGA实现ETH接口
单片机·嵌入式硬件·fpga开发
anghost15044 分钟前
基于单片机的智能声控窗帘
单片机·嵌入式硬件·mongodb
写bug写bug44 分钟前
你真的会用枚举吗
java·后端·设计模式
哆啦code梦1 小时前
趣谈设计模式之策略模式-比特咖啡给你一杯满满的情绪价值,让您在数字世界里”畅饮“
设计模式·策略模式
猫猫的小茶馆5 小时前
【STM32】HAL库中的实现(五):ADC (模数转换)
stm32·单片机·嵌入式硬件·mcu·51单片机·智能硬件·pcb工艺
华仔啊5 小时前
别学23种了!Java项目中最常用的6个设计模式,附案例
java·后端·设计模式
紫阡星影6 小时前
【模块系列】STM32&W25Q64
stm32·单片机·嵌入式硬件
keer_zu7 小时前
STM32L051同时处理Alarm A和Alarm B中断
stm32·单片机·嵌入式硬件
酷飞飞8 小时前
STC8单片机驱动I2C屏幕:实现时间、日期与温湿度显示
单片机·嵌入式硬件·51单片机·嵌入式
Keya9 小时前
MacOS端口被占用的解决方法
前端·后端·设计模式