Skip to content
← 返回设计模式列表
设计意图与对象责任

组合模式(Composite) ​

统一处理单个对象和对象树。

结构型

说明 ​

目录、菜单等递归结构可共用一个接口,容器递归委托给子节点。

分析 ​

Leaf 和 Group 都满足 Node,调用方可以对任意节点调用 Size。Group 递归汇总子节点的结果,因此对象树对外表现得像一个普通节点。

外层 Group 的 Size 等于一个叶子加上内层两个叶子,结果为 3;空 Group 的循环不执行,结果为 0。统一接口隐藏了递归,但没有保证结构一定是树:共享子树会重复计数,循环引用会递归不止,必须按业务明确是否允许。

查看图表代码

适用前提与边界 ​

设计递归结构时要决定空组、循环引用和错误传播应如何处理。 只有接口适配或独立变化确实存在时,才增加额外包装层。

示例输入与调用 ​

go
tree := Group{Children: []Node{Leaf{}, Group{Children: []Node{Leaf{}, Leaf{}}}}}
	fmt.Println(tree.Size())

运行输出 ​

text
3

完整 Go 示例 ​

go
package main

import "fmt"

type Node interface{ Size() int }
type Leaf struct{}

func (Leaf) Size() int {
	return 1
}

type Group struct{ Children []Node }

func (g Group) Size() int {
	n := 0
	for _, child := range g.Children {
		n += child.Size()
	}
	return n
}

func main() {
	tree := Group{Children: []Node{Leaf{}, Group{Children: []Node{Leaf{}, Leaf{}}}}}
	fmt.Println(tree.Size())
}

继续阅读