Golang设计模式之适配器模式介绍和代码示例

2023-12-05 0 404
目录
  • 概念示例
    • client.go: 客户端代码
    • computer.go: 客户端接口
    • mac.go: 服务
    • windows.go: 未知服务
    • windowsAdapter.go: 适配器
    • main.go
    • output.txt: 执行结果

概念示例

这里有一段客户端代码, 用于接收一个对象 (Lightning 接口) 的部分功能, 不过我们还有另一个名为 adaptee 的对象 (Windows 笔记本), 可通过不同的接口 (USB 接口) 实现相同的功能

这就是适配器模式发挥作用的场景。 我们可以创建这样一个名为 adapter 的结构体:

遵循符合客户端期望的相同接口 (Lightning 接口)。

可以适合被适配对象的方式对来自客户端的请求进行 “翻译”。 适配器能够接受来自 Lightning 连接器的信息, 并将其转换成 USB 格式的信号, 同时将信号传递给 Windows 笔记本的 USB 接口。

client.go: 客户端代码

package main
import \”fmt\”
type Client struct {
}
func (c *Client) InsertLightningConnectorIntoComputer(com Computer) {
fmt.Println(\”Client inserts Lightning connector into computer.\”)
com.InsertIntoLightningPort()
}

computer.go: 客户端接口

package main
type Computer interface {
InsertIntoLightningPort()
}

mac.go: 服务

package main
import \”fmt\”
type Mac struct {
}
func (m *Mac) InsertIntoLightningPort() {
fmt.Println(\”Lightning connector is plugged into mac machine.\”)
}

windows.go: 未知服务

package main
import \”fmt\”
type Windows struct{}
func (w *Windows) insertIntoUSBPort() {
fmt.Println(\”USB connector is plugged into windows machine.\”)
}

windowsAdapter.go: 适配器

package main
import \”fmt\”
type WindowsAdapter struct {
windowMachine *Windows
}
func (w *WindowsAdapter) InsertIntoLightningPort() {
fmt.Println(\”Adapter converts Lightning signal to USB.\”)
w.windowMachine.insertIntoUSBPort()
}

main.go

package main
func main() {
client := &Client{}
mac := &Mac{}
client.InsertLightningConnectorIntoComputer(mac)
windowsMachine := &Windows{}
windowsMachineAdapter := &WindowsAdapter{
windowMachine: windowsMachine,
}
client.InsertLightningConnectorIntoComputer(windowsMachineAdapter)
}

output.txt: 执行结果

Client inserts Lightning connector into computer.
Lightning connector is plugged into mac machine.
Client inserts Lightning connector into computer.
Adapter converts Lightning signal to USB.
USB connector is plugged into windows machine.

以上就是Golang适配器模式介绍和代码示例的详细内容,更多关于Golang适配器模式的资料请关注悠久资源网其它相关文章!

您可能感兴趣的文章:

  • Golang设计模式之适配器模式详细讲解
  • 一文详解Golang的中间件设计模式
  • Golang设计模式中抽象工厂模式详细讲解
  • Golang设计模式工厂模式实战写法示例详解
  • golang实现简单工厂、方法工厂、抽象工厂三种设计模式

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

悠久资源 Golang Golang设计模式之适配器模式介绍和代码示例 https://www.u-9.cn/jiaoben/golang/101809.html

常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务