Golang設(shè)計(jì)模式之適配器模式介紹和代碼示例
概念示例
這里有一段客戶端代碼, 用于接收一個(gè)對(duì)象 (Lightning 接口) 的部分功能, 不過我們還有另一個(gè)名為 adaptee 的對(duì)象 (Windows 筆記本), 可通過不同的接口 (USB 接口) 實(shí)現(xiàn)相同的功能
這就是適配器模式發(fā)揮作用的場景。 我們可以創(chuàng)建這樣一個(gè)名為 adapter 的結(jié)構(gòu)體:
遵循符合客戶端期望的相同接口 (Lightning 接口)。
可以適合被適配對(duì)象的方式對(duì)來自客戶端的請(qǐng)求進(jìn)行 “翻譯”。 適配器能夠接受來自 Lightning 連接器的信息, 并將其轉(zhuǎn)換成 USB 格式的信號(hào), 同時(shí)將信號(hào)傳遞給 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: 服務(wù)
package main import "fmt" type Mac struct { } func (m *Mac) InsertIntoLightningPort() { fmt.Println("Lightning connector is plugged into mac machine.") }
windows.go: 未知服務(wù)
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: 執(zhí)行結(jié)果
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適配器模式介紹和代碼示例的詳細(xì)內(nèi)容,更多關(guān)于Golang適配器模式的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
golang 實(shí)現(xiàn)tcp server端和client端,并計(jì)算RTT時(shí)間操作
這篇文章主要介紹了golang 實(shí)現(xiàn)tcp server端和client端,并計(jì)算RTT時(shí)間操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-12-12解決Go語言中高頻次和高并發(fā)下隨機(jī)數(shù)重復(fù)的問題
在Golang中,獲取隨機(jī)數(shù)的方法一般會(huì)介紹有兩種,一種是基于math/rand的偽隨機(jī),一種是基于crypto/rand的真隨機(jī),math/rand由于其偽隨機(jī)的原理,經(jīng)常會(huì)出現(xiàn)重復(fù)的隨機(jī)數(shù),導(dǎo)致在需要進(jìn)行隨機(jī)的業(yè)務(wù)出現(xiàn)較多的重復(fù)問題,所以本文給大家介紹了較好的解放方案2023-12-12