Golang设计模式之适配器模式介绍和代码示例
概念示例
这里有一段客户端代码, 用于接收一个对象 (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中使用proto3协议导致的空值字段不显示的问题处理方案
这篇文章主要介绍了golang中使用proto3协议导致的空值字段不显示的问题处理方案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2019-10-10
Golang如何对cron进行二次封装实现指定时间执行定时任务
这篇文章主要介绍了Golang如何对cron进行二次封装实现指定时间执行定时任务问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教2025-06-06


最新评论