Go中组合模式通过接口统一Leaf与Composite行为,Component接口强制实现Add/Remove/Operation等方法,Composite用[]Component切片和指针接收者管理子节点,Leaf仅实现方法而不持子节点,体现“容器即组件”的抽象本质。
Go 语言没有继承,但组合模式完全可行——关键不是“怎么模拟类继承”,而是“如何用接口 + 嵌入 + 多态表达树形容器关系”。
Component 接口统一叶子与容器行为组合模式的核心是让客户端无需区分单个对象(Leaf)和复合对象(Composite)。在 Go 中,这靠接口实现,而不是基类。定义一个 Component 接口,暴露所有需要被统一调用的方法,比如 Add、Remove、Operation:
type Component interface {
Operation() string
Add(c Component)
Remove(c Component)
GetChild(index int) Component
}
注意:Add 和 Remove 对叶子节点无意义,但接口必须提供——这是组合模式的契约。叶子实现时可 panic 或静默忽略,但不能缺失方法签名。
Composite
Composite 是真正持有子节点的容器,它必须能增删查子节点。推荐用切片保存 Component 接口值,并用指针接收者实现方法,确保修改生效:
type Composite struct {
children []Component
}
func (c *Composite) Add(child Component) {
c.children = append(c.children, child)
}
func (c *Composite) Remove(child Component) {
for i, ch := range c.children {
if ch == child {
c.children = append(c.children[:i], c.children[i+1:]...)
return
}
}
}
func (c *Composite) Get
Child(index int) Component {
if index < 0 || index >= len(c.children) {
return nil
}
return c.children[index]
}
func (c *Composite) Operation() string {
var res string
for _, child := range c.children {
res += child.Operation()
}
return "Composite: " + res
}
关键点:
children 类型是 []Component,不是具体结构体切片,否则无法存 Leaf
*Composite 接收者,否则 Add 修改的是副本,子节点加不进去GetChild 返回 Component,保持多态链完整;若返回具体类型,下游又得断言Leaf 是终端节点,不持有子节点,因此不需要切片或嵌入逻辑。它的实现极简:
type Leaf struct {
name string
}
func (l *Leaf) Operation() string {
return "Leaf(" + l.name + ")"
}
func (l *Leaf) Add(c Component) {
// 可选:panic("Leaf does not support Add") 或直接 return
}
func (l *Leaf) Remove(c Component) {}
func (l *Leaf) GetChild(index int) Component {
return nil
}
常见误区:
Leaf 加 children []Component 字段——冗余且误导,破坏语义清晰性Operation ——没问题;但若后续要支持修改内部状态(如计数器),就得改用指针Add/Remove 里 panic ——生产环境建议日志记录 + 静默忽略,除非明确要求强契约校验实际使用中,树的构建常涉及临时变量或局部作用域。例如:
root := &Composite{}
root.Add(&Leaf{name: "A"})
root.Add(&Composite{
children: []Component{&Leaf{name: "B1"}, &Leaf{name: "B2"}},
})
fmt.Println(root.Operation()) // 输出正常
这里容易出问题的地方:
&Leaf{...} 而非 Leaf{...}:因为 Component 接口方法是用指针接收者定义的,值类型无法满足接口(方法集不匹配)GetChild(i) 返回 nil 时,调用 .Operation() 会 panic ——务必在调用前判空,或由上层保证索引合法new(Leaf) 或 &Leaf{})组合模式在 Go 里不是语法糖,而是对“容器即组件”这一抽象的诚实表达。最易被忽略的其实是接口方法的完整性设计:一旦加了 Add,所有实现都得面对它——哪怕只是空实现。这不是缺陷,是契约的重量。