1. 概念
橋(Bridge)使用組合關(guān)系將代碼的實現(xiàn)層和抽象層分離,讓實現(xiàn)層與抽象層代碼可以分別自由變化。
例如 客戶端調(diào)用橋接接口實現(xiàn)原有功能和擴展功能的組合文章來源:http://www.zghlxwxcb.cn/news/detail-655964.html
1.1 角色
- Implementor(實施者):
- 具體實施者的抽象,可以是一個接口。
- Concrete Implementor(具體實施者):
- 可以理解為擴展之前的原有功能
- 橋接接口會在實現(xiàn)擴展功能的基礎(chǔ)上調(diào)用它實現(xiàn)這些原有功能
- Abstraction(抽象化):
- 我們可以理解為橋接接口,它在提供擴展功能的同時也橋接了原有功能的接口
- 為
Refined Abstraction
提供一個統(tǒng)一接口 - 它關(guān)聯(lián)了
Implementor
(或者進一步是Implementor
的聚合)
- Refined Abstraction(擴展抽象化):
- 可以理解為它實現(xiàn)了具體的擴展功能,并實際調(diào)用了
mplementor
接口完成了原有功能
- 可以理解為它實現(xiàn)了具體的擴展功能,并實際調(diào)用了
1.2 類圖
2. 代碼示例
2.1 設(shè)計
- 定義一個實施者
顏色
- 定義三個具體實施者
紅色
、綠色
、黃色
- 他們的
use()
方法來實現(xiàn)使用對應(yīng)顏色
- 他們的
- 定義一個抽象化類(橋接接口)
筆刷
- 定義兩個擴展抽象化類
粗筆刷
、細筆刷
- 他們的
畫畫
方法- 實現(xiàn)擴展功能——用對應(yīng)筆刷畫畫
- 同時調(diào)用實施者接口,實現(xiàn)了對應(yīng)的顏色功能
- 他們的
- 定義一個工廠函數(shù)用來實例化一個具體的
筆刷
- 調(diào)用
- 聲明一個實施者
- 實例化一個具體實施者
- 用具體實施者實例化一個橋接
- 調(diào)用橋接的方法實現(xiàn)原有功能和擴展功能的組合
2.1 代碼
package main
import "fmt"
//定義實施者類
type Color interface {
Use()
}
//定義具體實施者A
type Red struct{}
func (r Red) Use() {
fmt.Println("Use Red color")
}
//定義具體實施者B
type Green struct{}
func (g Green) Use() {
fmt.Println("Use Green color")
}
//定義具體實施者C
type Yellow struct{}
func (y Yellow) Use() {
fmt.Println("Use Yellow color")
}
// 定義抽象化類(或叫橋接接口)
type BrushPen interface {
DrawPicture()
}
// 定義擴展抽象化A
type BigBrushPen struct {
Color
}
//提供擴展功能,同時選擇原功能執(zhí)行
func (bbp BigBrushPen) DrawPicture() {
fmt.Println("Draw picture with big brush pen")
bbp.Use()
}
// 定義擴展抽象化B
type SmallBrushPen struct {
Color
}
//提供擴展功能,同時選擇原功能執(zhí)行
func (sbp SmallBrushPen) DrawPicture() {
fmt.Println("Draw picture with small brush pen")
sbp.Use()
}
// 定義工廠方法生產(chǎn)具體的擴展抽象化(此處為了方便展示,和橋接模式無關(guān))
func NewBrushPen(t string, color Color) BrushPen {
switch t {
case "BIG":
return BigBrushPen{
Color: color,
}
case "SMALL":
return SmallBrushPen{
Color: color,
}
default:
return nil
}
}
func main() {
//聲明實施者
var tColor Color
fmt.Println("========== 第一次測試 ==========")
//定義為具體實施者
tColor = Red{}
//用具體實施者實例化一個抽象化
tBrushPen := NewBrushPen("BIG", tColor)
//用抽象化的畫畫功能完成擴展功能(粗細筆刷)和對應(yīng)原功能(顏色)的組合操作
tBrushPen.DrawPicture()
fmt.Println("========== 第二次測試 ==========")
tColor = Green{}
tBrushPen = NewBrushPen("SMALL", tColor)
tBrushPen.DrawPicture()
fmt.Println("========== 第三次測試 ==========")
tColor = Yellow{}
tBrushPen = NewBrushPen("BIG", tColor)
tBrushPen.DrawPicture()
}
- 輸出
========== 第一次測試 ==========
Draw picture with big brush pen
Use Red color
========== 第二次測試 ==========
Draw picture with small brush pen
Use Green color
========== 第三次測試 ==========
Draw picture with big brush pen
Use Yellow color
2.2 類圖
文章來源地址http://www.zghlxwxcb.cn/news/detail-655964.html
到了這里,關(guān)于《golang設(shè)計模式》第二部分·結(jié)構(gòu)型模式-02-橋接模式(Bridge)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!