组合模式(Composite Pattern)是一种结构型设计模式,用于以树形结构来组织部分-整体的层次结构。这种模式创建了一个包含自己对象组的类,并允许客户端统一对待个别对象和组合对象。
组合模式通常包括以下几个组成部分:
以下是使用Go语言实现组合模式的示例:
package main
import (
"fmt"
"strings"
)
// 组件接口
type Component interface {
Add(Component)
Remove(Component)
Display(depth int)
}
// 叶子构件
type Leaf struct {
name string
}
func NewLeaf(name string) *Leaf {
return &Leaf{name: name}
}
func (l *Leaf) Add(c Component) {
fmt.Println("Cannot add to a leaf")
}
func (l *Leaf) Remove(c Component) {
fmt.Println("Cannot remove from a leaf")
}
func (l *Leaf) Display(depth int) {
fmt.Println(strings.Repeat("-", depth), l.name)
}
// 复合构件
type Composite struct {
name string
children []Component
}
func NewComposite(name string) *Composite {
return &Composite{name: name}
}
func (c *Composite) Add(child Component) {
c.children = append(c.children, child)
}
func (c *Composite) Remove(child Component) {
// 移除操作
}
func (c *Composite) Display(depth int) {
fmt.Println(strings.Repeat("-", depth), c.name)
for _, component := range c.children {
component.Display(depth + 2)
}
}
func main() {
root := NewComposite("root")
root.Add(NewLeaf("Leaf A"))
root.Add(NewLeaf("Leaf B"))
comp := NewComposite("Composite X")
comp.Add(NewLeaf("Leaf XA"))
comp.Add(NewLeaf("Leaf XB"))
root.Add(comp)
root.Display(1)
}
组合模式适用于以下场景:
优点:
缺点:
组合模式为处理类似树形结构的场景提供了非常有用的模型,它可以使整体和部分的操作具有一致性,使得客户端操作更加简便。