Golang學習筆記_31——原型模式
Golang學習筆記_32——適配器模式
Golang學習筆記_33——橋接模式
文章目錄
- 一、核心概念
- 1. 定義
- 2. 解決的問題
- 3. 核心角色
- 4. 類圖
- 二、特點分析
- 三、適用場景
- 1. 文件系統
- 2. 圖形界面
- 3. 組織架構
- 四、代碼示例(Go語言)
- 五、高級應用
- 1. 遞歸統計
- 2. 組合模式 + 訪問者模式
- 六、與其他模式對比
- 七、總結
一、核心概念
1. 定義
組合模式(Composite Pattern)是一種結構型設計模式,通過將對象組織成樹形結構來表示“部分-整體”的層次關系,使客戶端可以統一處理單個對象和組合對象。
2. 解決的問題
- 樹形結構表示:需要處理具有層級關系的對象(如文件系統、組織架構)
- 統一操作接口:消除客戶端對葉子節點和組合節點的差異感知
- 遞歸遍歷需求:需要遞歸處理嵌套結構(如計算文件夾總大小)
3. 核心角色
-
Component(抽象組件)
定義所有對象的通用接口,聲明管理子組件的方法(如Add()
、Remove()
)和業務方法(如Display()
) -
Leaf(葉子節點)
樹形結構的末端節點,沒有子節點,實現具體業務邏輯 -
Composite(組合節點)
包含子節點的容器,實現組件接口并管理子組件集合
4. 類圖
二、特點分析
優點
-
統一接口
客戶端無需區分葉子節點和組合節點,簡化調用邏輯 -
靈活擴展
新增組件類型無需修改現有代碼,符合開閉原則 -
層次清晰
天然支持樹形結構表示,便于處理遞歸操作
缺點
-
設計復雜度高
需要定義抽象接口并處理遞歸邏輯,增加實現難度 -
類型限制困難
難以約束容器節點只能包含特定類型子組件
三、適用場景
1. 文件系統
- 葉子節點:文件
- 組合節點:文件夾(可包含文件/子文件夾)
- 操作:遞歸計算總大小、展示目錄結構
2. 圖形界面
- 葉子節點:按鈕、文本框
- 組合節點:面板、窗口
- 操作:統一渲染、事件處理
3. 組織架構
- 葉子節點:員工
- 組合節點:部門
- 操作:統計總人數、打印層級關系
四、代碼示例(Go語言)
package compositedemoimport "fmt"// Component 接口
type Component interface {Display(indent string)
}// Leaf 葉子節點
type File struct {Name string
}func (l *File) Display(indent string) {println(indent + l.Name)
}// Directory 組合節點
type Directory struct {Name stringComponent []Component
}func (c *Directory) Display(indent string) {println(indent + c.Name)for _, component := range c.Component {component.Display(indent + indent)}
}func (c *Directory) Add(component Component) {c.Component = append(c.Component, component)
}func (c *Directory) Remove(component Component) {for i, v := range c.Component {if v == component {c.Component = append(c.Component[:i], c.Component[i+1:]...)}}
}func test() {root := &Directory{Name: "root"}directory := &Directory{Name: "directory"}file1 := &File{Name: "file1"}file2 := &File{Name: "file2"}root.Add(directory)directory.Add(file1)directory.Add(file2)root.Display("--")fmt.Println("==========================================")directory.Display("**")
}
=== RUN Test_test
--root
----directory
--------file1
--------file2
==========================================
**directory
****file1
****file2
--- PASS: Test_test (0.00s)
PASS
五、高級應用
1. 遞歸統計
// 在Component接口添加方法
type FileSystemComponent interface {Size() int
}// File實現
func (f *File) Size() int {return 1024 // 假設固定大小
}// Directory實現
func (d *Directory) Size() int {total := 0for _, child := range d.children {total += child.Size()}return total
}
2. 組合模式 + 訪問者模式
通過訪問者模式實現更復雜的樹形結構操作(如格式轉換、權限檢查)
六、與其他模式對比
模式 | 核心目標 | 關鍵區別 |
---|---|---|
裝飾器 | 動態添加功能 | 通過嵌套包裝擴展功能 |
適配器 | 接口轉換 | 解決接口不兼容問題 |
迭代器 | 遍歷集合元素 | 專注于遍歷算法實現 |
七、總結
組合模式通過樹形結構和統一接口,有效解決了以下問題:
- 層次結構表示:天然適合文件系統、組織架構等場景
- 遞歸操作簡化:通過統一接口實現遞歸遍歷
- 擴展性提升:新增組件類型不影響現有結構
在Go語言中實現時需注意:
- 通過接口實現多態特性
- 使用切片管理子組件集合
- 謹慎處理葉子節點的無效方法(如
Add()
)