go 示例

最后更新于:2022-04-02 04:19:55

[TOC] ## 示例 ### 文件系统
main.go ``` 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") } ```

输出 ``` 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 ```
';