8. 组合模式(Composite)
8. 组合模式(Composite)
问题:想统一对待单个对象和组合对象(如文件与文件夹)。
核心:定义统一接口,叶子和容器都实现它,容器递归调用子元素。
class File {
constructor(name) { this.name = name; }
display(indent = '') { console.log(`${indent}- ${this.name}`); }
}
class Folder {
constructor(name) { this.name = name; this.children = []; }
add(child) { this.children.push(child); return this; }
display(indent = '') {
console.log(`${indent}📁 ${this.name}`);
this.children.forEach(c => c.display(indent + ' '));
}
}
const root = new Folder('项目')
.add(new File('index.js'))
.add(new Folder('src').add(new File('app.js')).add(new File('utils.js')));
root.display();
// 📁 项目
// - index.js
// 📁 src
// - app.js
// - utils.jspackage composite
import "fmt"
type Component interface {
Display(indent string)
}
type File struct{ Name string }
func (f File) Display(indent string) {
fmt.Printf("%s- %s\n", indent, f.Name)
}
type Folder struct {
Name string
Children []Component
}
func (f *Folder) Add(c Component) *Folder {
f.Children = append(f.Children, c)
return f
}
func (f *Folder) Display(indent string) {
fmt.Printf("%s📁 %s\n", indent, f.Name)
for _, child := range f.Children {
child.Display(indent + " ")
}
}