5.组合模式
组合模式(Composite Pattern)的主要目的是:把 "整体-部分" 结构统一成同一套接口,让调用方可以一致地处理单个对象和对象集合
重要
就是把 "单个对象" 和 "对象集合" 当成同一种对象来用
适合使用组合模式的场景
- 菜单系统
- 路由树
- 文件目录树
统一接口
interface Node {
render(indent?: number): void;
}叶子节点与容器节点
class FileNode implements Node {
constructor(private name: string) {}
render(indent = 0): void {
console.log(`${" ".repeat(indent)}- ${this.name}`);
}
}
class FolderNode implements Node {
private children: Node[] = [];
constructor(private name: string) {}
add(node: Node): void {
this.children.push(node);
}
render(indent = 0): void {
console.log(`${" ".repeat(indent)}+ ${this.name}`);
this.children.forEach((child) => child.render(indent + 2));
}
}使用示例
const root = new FolderNode("src");
root.add(new FileNode("main.ts"));
const components = new FolderNode("components");
components.add(new FileNode("Button.tsx"));
components.add(new FileNode("Card.tsx"));
root.add(components);
root.render();在这个案例中让单个对象 FileNode 和对象集合 FolderNode 都实现了同一个 render 方法。这样在调用时就不需要关心它们的区别,可以一致地调用 render 方法来渲染整个树形结构
