【设计模式】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()
}
相关推荐
choumin21 小时前
创建型模式——工厂方法模式
c++·设计模式·工厂方法模式·创建型模式
Zevalin爱灰灰1 天前
能源与电源管理电路——防倒灌电路
单片机·嵌入式硬件·电源管理
jianqiang.xue1 天前
ESP-IDF保姆级入门02|Ubuntu24.04搭建EIM-GUI开发环境,打通Windows_Linux双平台统一开发
stm32·单片机·物联网
嵌入式-老费1 天前
esp32开发与应用(添加数据分区)
单片机·嵌入式硬件
choumin1 天前
创建型模式——原型模式
c++·设计模式·原型模式·创建型模式
37.2℃9951 天前
Claude Design哪个公司技术好
python·设计模式
阿懂在掘金1 天前
Vue 弹窗新范式——代码减少、复用翻倍与 AI 时代的前端基建
前端·设计模式·前端框架
CYLAM20251 天前
STC32G 单片机0.96“OLED 西历农历可调万年历 (1901-2100)
单片机·嵌入式硬件·stc32g·万年历·西历农历·0.96”oled 12864·4x4 矩阵键盘
choumin1 天前
结构型模式——装饰模式
c++·设计模式·装饰模式·结构型模式
Discipline~Hai1 天前
ARM03-蜂鸣器和中断
c语言·arm开发·单片机·嵌入式硬件·嵌入式