Golang橋接模式講解和代碼示例
層次結(jié)構(gòu)中的第一層 (通常稱為抽象部分) 將包含對第二層 (實現(xiàn)部分) 對象的引用。 抽象部分將能將一些 (有時是絕大部分) 對自己的調(diào)用委派給實現(xiàn)部分的對象。 所有的實現(xiàn)部分都有一個通用接口, 因此它們能在抽象部分內(nèi)部相互替換。
概念示例
假設(shè)你有兩臺電腦: 一臺 Mac 和一臺 Windows。 還有兩臺打印機: 愛普生和惠普。 這兩臺電腦和打印機可能會任意組合使用。 客戶端不應去擔心如何將打印機連接至計算機的細節(jié)問題。
如果引入新的打印機, 我們也不會希望代碼量成倍增長。 所以, 我們創(chuàng)建了兩個層次結(jié)構(gòu), 而不是 2x2 組合的四個結(jié)構(gòu)體:
- 抽象層: 代表計算機
- 實施層: 代表打印機
這兩個層次可通過橋接進行溝通, 其中抽象層 (計算機) 包含對于實施層 (打印機) 的引用。 抽象層和實施層均可獨立開發(fā), 不會相互影響。
computer.go: 抽象
package main
type Computer interface {
Print()
SetPrinter(Printer)
}mac.go: 精確抽象
package main
import "fmt"
type Mac struct {
printer Printer
}
func (m *Mac) Print() {
fmt.Println("Print request for mac")
m.printer.PrintFile()
}
func (m *Mac) SetPrinter(p Printer) {
m.printer = p
}windows.go: 精確抽象
package main
import "fmt"
type Windows struct {
printer Printer
}
func (w *Windows) Print() {
fmt.Println("Print request for windows")
w.printer.PrintFile()
}
func (w *Windows) SetPrinter(p Printer) {
w.printer = p
}printer.go: 實施
package main
type Printer interface {
PrintFile()
}epson.go: 具體實施
package main
import "fmt"
type Epson struct {}
func (p \*Epson) PrintFile() {
fmt.Println("Printing by a EPSON Printer")
}hp.go: 具體實施
package main
import "fmt"
type Hp struct {}
func (p *Hp) PrintFile() {
fmt.Println("Printing by a HP Printer")
}main.go: 客戶端代碼
package main
import "fmt"
func main() {
hpPrinter := &Hp{}
epsonPrinter := &Epson{}
macComputer := &Mac{}
macComputer.SetPrinter(hpPrinter)
macComputer.Print()
fmt.Println()
macComputer.SetPrinter(epsonPrinter)
macComputer.Print()
fmt.Println()
winComputer := &Windows{}
winComputer.SetPrinter(hpPrinter)
winComputer.Print()
fmt.Println()
winComputer.SetPrinter(epsonPrinter)
winComputer.Print()
fmt.Println()
}output.txt: 執(zhí)行結(jié)果
Print request for mac
Printing by a HP PrinterPrint request for mac
Printing by a EPSON PrinterPrint request for windows
Printing by a HP PrinterPrint request for windows
以上就是Golang橋接模式講解和代碼示例的詳細內(nèi)容,更多關(guān)于Golang 橋接模式的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
使用Go基于WebSocket構(gòu)建千萬級視頻直播彈幕系統(tǒng)的代碼詳解
這篇文章主要介紹了使用Go基于WebSocket構(gòu)建千萬級視頻直播彈幕系統(tǒng),本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-07-07
Go json omitempty如何實現(xiàn)可選屬性
在Go語言中,使用`omitempty`可以幫助我們在進行JSON序列化和反序列化時,忽略結(jié)構(gòu)體中的零值或空值,本文介紹了如何通過將字段類型改為指針類型,并在結(jié)構(gòu)體的JSON標簽中添加`omitempty`來實現(xiàn)這一功能,例如,將float32修改為*float322024-09-09
golang中struct和[]byte的相互轉(zhuǎn)換示例
這篇文章主要介紹了golang中struct和[]byte的相互轉(zhuǎn)換示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-07-07
破解IDEA(Goland)注冊碼設(shè)置 license server一直有效不過期的過程詳解
這篇文章主要介紹了破解IDEA(Goland)注冊碼設(shè)置 license server一直有效不過期,本文通過圖文并茂的形式給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-11-11

