文章目錄
- 1. 概念
- 1.1 角色
- 1.2 類圖
- 2. 代碼示例
- 2.1 設計
- 2.1 代碼
- 2.2 類圖
1. 概念
客戶端調用橋接接口實現原有功能和擴展功能的組合
1.1 角色
- Implementor(實施者):
- 具體實施者的抽象,可以是一個接口。
- Concrete Implementor(具體實施者):
- 可以理解為擴展之前的原有功能
- 橋接接口會在實現擴展功能的基礎上調用它實現這些原有功能
- Abstraction(抽象化):
- 我們可以理解為橋接接口,它在提供擴展功能的同時也橋接了原有功能的接口
- 為
Refined Abstraction
提供一個統一接口 - 它關聯了
Implementor
(或者進一步是Implementor
的聚合)
- Refined Abstraction(擴展抽象化):
- 可以理解為它實現了具體的擴展功能,并實際調用了
mplementor
接口完成了原有功能
- 可以理解為它實現了具體的擴展功能,并實際調用了
1.2 類圖
2. 代碼示例
2.1 設計
- 定義一個實施者
顏色
- 定義三個具體實施者
紅色
、綠色
、黃色
- 他們的
use()
方法來實現使用對應顏色
- 他們的
- 定義一個抽象化類(橋接接口)
筆刷
- 定義兩個擴展抽象化類
粗筆刷
、細筆刷
- 他們的
畫畫
方法- 實現擴展功能——用對應筆刷畫畫
- 同時調用實施者接口,實現了對應的顏色功能
- 他們的
- 定義一個工廠函數用來實例化一個具體的
筆刷
- 調用
- 聲明一個實施者
- 實例化一個具體實施者
- 用具體實施者實例化一個橋接
- 調用橋接的方法實現原有功能和擴展功能的組合
2.1 代碼
package mainimport "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
}//提供擴展功能,同時選擇原功能執行
func (bbp BigBrushPen) DrawPicture() {fmt.Println("Draw picture with big brush pen")bbp.Use()
}// 定義擴展抽象化B
type SmallBrushPen struct {Color
}
//提供擴展功能,同時選擇原功能執行
func (sbp SmallBrushPen) DrawPicture() {fmt.Println("Draw picture with small brush pen")sbp.Use()
}// 定義工廠方法生產具體的擴展抽象化(此處為了方便展示,和橋接模式無關)
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 Colorfmt.Println("========== 第一次測試 ==========")//定義為具體實施者tColor = Red{}//用具體實施者實例化一個抽象化tBrushPen := NewBrushPen("BIG", tColor)//用抽象化的畫畫功能完成擴展功能(粗細筆刷)和對應原功能(顏色)的組合操作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