【设计模式】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()
}
相关推荐
悠哉悠哉愿意15 小时前
【单片机学习笔记】串口、超声波、NE555的同时使用
笔记·单片机·学习
Lester_110117 小时前
STM32霍尔传感器输入口设置为复用功能输入口时,还能用GPIO函数直接读取IO的状态吗
stm32·单片机·嵌入式硬件·电机控制
三佛科技-1873661339717 小时前
120W小体积碳化硅电源方案(LP8841SC极简方案12V10A/24V5A输出)
单片机·嵌入式硬件
z203483152017 小时前
STM32F103系列单片机定时器介绍(二)
stm32·单片机·嵌入式硬件
Alaso_shuang20 小时前
STM32 核心输入、输出模式
stm32·单片机·嵌入式硬件
2501_9181269121 小时前
stm32死锁是怎么实现的
stm32·单片机·嵌入式硬件·学习·个人开发
z203483152021 小时前
STM32F103系列单片机定时器介绍(一)
stm32·单片机
星马梦缘1 天前
驱动层开发——蜂鸣器驱动
stm32·单片机·嵌入式硬件·hal·驱动
阿闽ooo1 天前
中介者模式打造多人聊天室系统
c++·设计模式·中介者模式
小刘爱玩单片机1 天前
【stm32简单外设篇】- 测速传感器模块(光电)
c语言·stm32·单片机·嵌入式硬件