組合模式是指將一組相似對象當做一個單一對象的設計模式.
1.組成角色:
1.1組件:
組合中的對象聲明接口,主要用于訪問和管理其子組件.
1.2葉子節點:
定義組合中原始對象行為的類.葉子節點表示組合中的葉對象.
1.3組合:
又稱為容器,存儲子組件并在組件接口中實現與子組件有關的類.
1.4客戶端:
客戶端可以通過組件接口操作組合中的對象.以及與樹形結構中的所有項目交互.
2.使用場景:
2.1需要忽略組合對象和單個對象之間差異時.
2.2需要實現樹形結構時.
2.3客戶端以統一的方式處理簡單或復雜的元素.
3.實現:
3.1組件接口:
// 組件接口
type Component interface {Execute()
}
3.2葉節點類:
// 葉子節點類
type Leaf struct {value int
}// 創建一個新的葉節點對象
func NewLeaf(value int) *Leaf {return &Leaf{value: value}
}// 打印葉節點的值
func (l *Leaf) Execute() {fmt.Println(l.value)
}
3.3組合類:
// 組合類
type Composite struct {children []Component
}// 創建一個新的組合對象
func NewComposite() *Composite {return &Composite{make([]Component, 0)}
}
3.4組合類中添加方法:
// 添加方法
func (c *Composite) Add(component Component) {c.children = append(c.children, component)
}func (c *Composite) Execute() {for _, child := range c.children {child.Execute()}
}
3.5客戶端:
func main() {composite := itboStudy.NewComposite()leaf := itboStudy.NewLeaf(99)leaf1 := itboStudy.NewLeaf(88)leaf2 := itboStudy.NewLeaf(77)composite.Add(leaf)composite.Add(leaf1)composite.Add(leaf2)composite.Execute()
}
4.實戰:
4.1葉子節點:
// 葉子節點類
type Files struct {Name string
}func (f *Files) Search(name string) {fmt.Printf("在文件%s中遞歸搜索%s", f.Name, name)
}func (f *Files) GetName() string {return f.Name
}
4.2組合類:
// 定義組合類.
type Folders struct {Compents []ComponentsName string
}func (f *Folders) Search(name string) {fmt.Printf("在文件%s中遞歸搜索%s", f.Name, name)for i := range f.Compents {f.Compents[i].Search(name)}
}func (f *Folders) Add(c Components) {f.Compents = append(f.Compents, c)
}
4.3組件接口:
// 定義組件接口
type Components interface {Search(name string)
}
4.4客戶端:
func main() {file1 := &itboStudy.Files{Name: "itboStudy1"}file2 := &itboStudy.Files{Name: "itboStudy2"}file3 := &itboStudy.Files{Name: "itboStudy3"}folders := &itboStudy.Folders{Name: "itboFolder"}folders.Add(file1)folders.Add(file2)folders.Add(file3)folders.Search("99")
}
5.優點:
無須了解構成樹形結構的對象具體類,只需要調用接口方法.
客戶端可以使用組件對象與復合結構中的對象進行交互.
如果調用的是葉子節點對象,可以直接處理請求.
如果調用的組合對象,組合模式會把請求轉發給子組件.
6.缺點:
一旦定義了樹結構,設計會過于籠統.
組合模式很難將樹的組件限制為特定類型.
為了強制執行這種約束,程序必須依賴運行時檢查.組合模式不能使用編程語言的類型系統.
士別三日當刮目相待.