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

八、adapter 适配器模式

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

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

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

8.1 convert_lightning_to_usb

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

08adapter/081convert_lightning_to_usb
├── adapter.go
├── client.go
├── client_test.go
├── computer.go
└── readme.md

8.1.1 client_test.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

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

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

package _81convert_lightning_to_usb

import "fmt"

type windowsAdapter struct {
	windowsComputer *windows
}

func (a *windowsAdapter) InsertIntoLightningPort() {
	fmt.Println("适配器: 将雷电口转换为USB口")
	a.windowsComputer.InsertIntoUSBPort()
}

相关推荐

  1. 设计模式8adapter 适配器模式

    2024-04-22 00:22:02       32 阅读
  2. 设计模式-适配器模式 Adapter

    2024-04-22 00:22:02       48 阅读
  3. 设计模式——适配器模式Adapter

    2024-04-22 00:22:02       34 阅读
  4. .NET 设计模式适配器模式Adapter Pattern)

    2024-04-22 00:22:02       47 阅读
  5. 设计模式适配器模式Adapter Pattern)

    2024-04-22 00:22:02       35 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-22 00:22:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-22 00:22:02       101 阅读
  3. 在Django里面运行非项目文件

    2024-04-22 00:22:02       82 阅读
  4. Python语言-面向对象

    2024-04-22 00:22:02       91 阅读

热门阅读

  1. 考古:MFC界面的自适应缩放(代码示例)

    2024-04-22 00:22:02       36 阅读
  2. Leetcode 104. 二叉树的最大深度

    2024-04-22 00:22:02       34 阅读
  3. 突破编程_C++_网络编程(Boost.Asio(简介))

    2024-04-22 00:22:02       26 阅读
  4. 【C++刷题】优选算法——动态规划第四辑

    2024-04-22 00:22:02       35 阅读
  5. 【LeetCode热题100】【动态规划】最长递增子序列

    2024-04-22 00:22:02       37 阅读
  6. 2015NOIP普及组真题 2. 扫雷游戏

    2024-04-22 00:22:02       32 阅读