ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
[TOC] ## 示例 ### 文件系统 <details> <summary>main.go</summary> ``` package main import "fmt" // 叶子 type component interface { search(string) } // 组件接口 type file struct { name string } func (f *file) search(keyword string) { fmt.Printf("Searching for keyword %s in file %s\n", keyword, f.name) } func (f *file) getName() string { return f.name } // 组合 type folder struct { components []component name string } func (f *folder) search(keyword string) { fmt.Printf("Serching recursively for keyword %s in folder %s\n", keyword, f.name) for _, composite := range f.components { composite.search(keyword) } } func (f *folder) add(c component) { f.components = append(f.components, c) } func main() { folder1 := &folder{ name: "Folder1", } file1 := &file{name: "File1"} folder1.add(file1) folder2 := &folder{ name: "Folder2", } file2 := &file{name: "File2"} file3 := &file{name: "File3"} folder2.add(file2) folder2.add(file3) folder2.add(folder1) folder2.search("rose") } ``` </details> <br /> 输出 ``` Serching recursively for keyword rose in folder Folder2 Searching for keyword rose in file File2 Searching for keyword rose in file File3 Serching recursively for keyword rose in folder rose Searching for keyword rose in file File1 ```