我们一起来读书吧 关注:154贴子:2,823
  • 0回复贴,共1

适配器模式

只看楼主收藏回复

当你希望使用某个类, 但是其接口与其他代码不兼容时, 可以使用适配器类。
适配器可担任两个对象间的封装器, 它会接收对于一个对象的调用, 并将其转换为另一个对象可识别的格式和接口。
这里是一个闪电接口硬盘插入windows电脑的场景
main.go文件
package adapter
import (
"fmt"
"testing"
)
// 我有个硬盘是 闪电接口,现在我需要把硬盘插到 一个只有USB接口的Windows电脑上,怎么实现?
func TestAdapter(t *testing.T) {
client := &Client{}
mac := &Mac{}
client.InsertLightningConnectorIntoComputer(mac)
fmt.Println("尝试插入到windows电脑 ==============================")
windowsMachine := &Windows{}
windowsMachineAdapter := &WindowsAdapter{
windowMachine: windowsMachine,
}
client.InsertLightningConnectorIntoComputer(windowsMachineAdapter)
}
client.go 文件
import "fmt"
type Client struct {
}
// InsertLightningConnectorIntoComputer 将闪电接头插入到计算机的闪电端口
func (c *Client) InsertLightningConnectorIntoComputer(com Computer) {
fmt.Println("开始连接硬盘")
com.InsertIntoLightningPort()
fmt.Println("硬盘链接电脑成功")
}
mac.go 文件
import "fmt"
type Mac struct {
}
func (m *Mac) InsertIntoLightningPort() {
fmt.Println("插入闪电接口")
}
window.go 文件
import "fmt"
type Windows struct{}
func (w *Windows) insertIntoUSBPort() {
fmt.Println("插入USB接口")
}


IP属地:北京1楼2024-09-26 21:16回复