擴充卡模式
擴充卡是一種結構型設計模式, 它能使不相容的對象能夠互相合作。
擴充卡可擔任兩個對象間的封裝器, 它會接收對于一個對象的調用, 并将其轉換為另一個對象可識别的格式和接口。

概念示例
這裡有一段用戶端代碼, 用于接收一個對象 (Lightning 接口) 的部分功能, 不過我們還有另一個名為 adaptee 的對象 (Windows 筆記本), 可通過不同的接口 (USB 接口) 實作相同的功能
這就是擴充卡模式發揮作用的場景。 我們可以建立這樣一個名為 adapter 的結構體:
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.