Golang橋接模式講解和代碼示例
層次結(jié)構(gòu)中的第一層 (通常稱為抽象部分) 將包含對第二層 (實現(xiàn)部分) 對象的引用。 抽象部分將能將一些 (有時是絕大部分) 對自己的調(diào)用委派給實現(xiàn)部分的對象。 所有的實現(xiàn)部分都有一個通用接口, 因此它們能在抽象部分內(nèi)部相互替換。
概念示例
假設(shè)你有兩臺電腦: 一臺 Mac 和一臺 Windows。 還有兩臺打印機: 愛普生和惠普。 這兩臺電腦和打印機可能會任意組合使用。 客戶端不應(yīng)去擔(dān)心如何將打印機連接至計算機的細(xì)節(jié)問題。
如果引入新的打印機, 我們也不會希望代碼量成倍增長。 所以, 我們創(chuàng)建了兩個層次結(jié)構(gòu), 而不是 2x2 組合的四個結(jié)構(gòu)體:
- 抽象層: 代表計算機
- 實施層: 代表打印機
這兩個層次可通過橋接進(jìn)行溝通, 其中抽象層 (計算機) 包含對于實施層 (打印機) 的引用。 抽象層和實施層均可獨立開發(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橋接模式講解和代碼示例的詳細(xì)內(nèi)容,更多關(guān)于Golang 橋接模式的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Golang中本地緩存庫cache2go的使用小結(jié)
本文介紹了Go語言本地緩存庫cache2go的使用方法和源碼分析,cache2go提供了并發(fā)安全的讀寫操作,支持過期時間控制,下面就來詳細(xì)的介紹cache2go如何創(chuàng)建、添加、讀取、刪除緩存項及設(shè)置回調(diào)函數(shù),感興趣的可以了解一下2026-04-04
Go 通過結(jié)構(gòu)struct實現(xiàn)接口interface的問題
這篇文章主要介紹了Go 通過結(jié)構(gòu)struct實現(xiàn)接口interface的問題,本文通過示例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-10-10
linux中用shell快速安裝配置Go語言的開發(fā)環(huán)境
相信每位開發(fā)者都知道選擇一門開發(fā)語言,免不了需要安裝配置開發(fā)環(huán)境,所以這篇文章給大家分享了linux下使用shell一鍵安裝配置GO語言開發(fā)環(huán)境的方法,有需要的朋友們可以參考借鑒,下面來一起看看吧。2016-10-10
Go 語言json.Unmarshal 遇到的小問題(推薦)
這篇文章主要介紹了 Go 語言json.Unmarshal 遇到的小問題,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-07-07
詳解Golang如何優(yōu)雅接入多個遠(yuǎn)程配置中心
這篇文章主要為大家為大家介紹了Golang如何優(yōu)雅接入多個遠(yuǎn)程配置中心詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-05-05

