如何使用Golang实现组合模式管理树形结构_统一处理节点与子节点

Go组合模式通过统一Component接口实现树形结构管理,Leaf(如File)和Composite(如Directory)均实现该接口,支持无差别调用GetName、Print、Size等方法,新增节点类型只需实现接口,无需修改现有逻辑。

用 Go 实现组合模式管理树形结构,核心在于让节点(Leaf)和子树(Composite)实现同一接口,从而对它们进行统一操作——无需区分是单个元素还是容器,调用方式完全一致。

定义统一组件接口

所有节点类型都实现 Component 接口,包含基本行为:获取名称、打印结构、计算大小(或其他业务逻辑)等。这是组合模式的基石。

例如:

type Component interface {
    GetName() string
    Print(indent string)
    Size() int
}

这样,无论后续是文件(Leaf)还是目录(Composite),外部代码都只依赖这个接口,不关心具体类型。

实现叶子节点(Leaf)

叶子节点不包含子节点,它的行为是自包含的。比如一个文件:

type File struct {
    name string
    size int
}

func (f File) GetName() string { return f.name } func (f File) Print(indent string) { fmt.Printf("%s- %s (file, %d bytes)\n", indent, f.name, f.size) } func (f *File) Size() int { return f.size }

它直接返回自身信息,不递归,也不处理子项。

实现容器节点(Composite)

容器节点持有多个 Component,它把请求转发给子节点,并可能聚合结果:

type Directory struct {
    name     string
    children []Component
}

func (d Directory) GetName() string { return d.name } func (d Directory) Print(indent string) { fmt.Printf("%s+ %s (dir)\n", indent, d.name) for , c := range d.children { c.Print(indent + " ") } } func (d *Directory) Size() int { total := 0 for , c := range d.children { total += c.Size() } return total }

关键点:

  • children 切片类型为 []Component,可混存 File、Directory 或其他实现类
  • Print 和 Size 方法都递归调用子节点的同名方法,天然支持任意深度嵌套
  • 新增节点类型(如 SymbolicLink、ZipArchive)只需实现 Component,无需修改现有 Composite 逻辑

构建与使用树结构

组合模式的优势在构造和调用时最明显——客户端代码完全无感节点类型差异:

root := &Directory{name: "root"}
src := &Directory{name: "src"}
mainFile := &File{name: "main.go", size: 1240}
goMod := &File{name: "go.mod", size: 86}

src.children = append(src.children, mainFile, goMod) root.children = append(root.children, src, &File{name: "README.md", size: 520})

root.Print("") // 统一调用,自动展开整棵树 fmt.Println("Total size:", root.Size()) // 自动累加所有叶子大小

你会发现,添加新层级、替换某节点、遍历或统计,都不需要 if/switch 判断类型——Go 的接口多态和组合模式天然契合。