1. 程式人生 > 其它 >結構型:五. 橋接模式

結構型:五. 橋接模式

橋接模式是什麼

橋接模式:橋接是一種結構型設計模式, 可將業務邏輯或一個大類拆分為不同的層次結構, 從而能獨立地進行開發。

為什麼用橋接模式

對於兩個獨立變化的維度,使用橋接模式再適合不過了.

橋接模式怎麼實現

這裡是將computer和printer分成兩層,用介面的方式把強耦合轉化為弱耦合。這兩個層次可通過橋接進行溝通, 其中抽象層 (computer) 包含對於實施層 (printer) 的引用。 抽象層和實施層均可獨立開發, 不會相互影響。

computer.go
package bridge

import "fmt"

type computer interface {
    print()
    setPrinter(printer)
}

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
}

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 bridge

import "fmt"

type printer interface {
    printFile()
}

type epson struct {
}

func (p *epson) printFile() {
    fmt.Println("Printing by a EPSON Printer")
}

type hp struct {
}

func (p *hp) printFile() {
    fmt.Println("Printing by a HP Printer")
}

main.go 客戶端程式碼
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()
}

// 結果:
//Print request for mac
//Printing by a HP Printer
//
//Print request for mac
//Printing by a EPSON Printer
//
//Print request for windows
//Printing by a HP Printer
//
//Print request for windows
//Printing by a EPSON Printer

優點

  1. 橋接模式使層次結構更清晰,系統更具擴充套件性。
  2. 橋接模式使系統更靈活,實現了抽象化與實現化的脫耦。他們兩個互相獨立,不會影響到對方。

缺點

  1. 橋接模式的引入會增加系統的理解與設計難度,由於聚合關聯關係建立在抽象層,要求開發者針對抽象進行設計與程式設計。
  2. 橋接模式要求正確識別出系統中兩個獨立變化的維度,因此其使用範圍具有一定的侷限性