组合模式(Composite Pattern)
组合模式(Composite Pattern)是一种结构型设计模式,它允许你将对象组合成树状结构以表示“部分-整体”的层次结构。组合模式允许客户端代码以统一的方式处理单个对象和对象组合,从而将它们视为同一种类型的对象。
场景
图形用户界面(GUI):组合模式可用于创建复杂的用户界面,其中包含各种控件(按钮、文本框、面板等),这些控件可以作为单个控件或组合在一起。
文件系统:文件系统中的文件和文件夹可以使用组合模式表示,从而可以递归地操作文件和文件夹。
组织结构:在组织机构中,可以使用组合模式表示部门、员工和其他层次结构。
图形和图表:绘制图形和图表时,可以使用组合模式来表示复杂的结构,如流程图、树状图等。
实现
// 组件接口
class Component {
constructor(name) {
this.name = name;
}
// 通用操作
operation() {
throw new Error("Operation not supported");
}
}
// 叶子节点
class File extends Component {
operation() {
return `File: ${this.name}`;
}
}
// 容器节点
class Folder extends Component {
constructor(name) {
super(name);
this.children = [];
}
add(child) {
this.children.push(child);
}
operation() {
const result = [`Folder: ${this.name}`];
for (const child of this.children) {
result.push(` ${child.operation()}`);
}
return result.join("\n");
}
}
// 使用组合模式表示文件系统
const root = new Folder("Root");
const folder1 = new Folder("Folder 1");
const folder2 = new Folder("Folder 2");
const file1 = new File("File 1");
const file2 = new File("File 2");
folder1.add(file1);
folder2.add(file2);
root.add(folder1);
root.add(folder2);
console.log(root.operation());
在上面的示例中,Component 是组件接口,它定义了通用的操作方法。File 是叶子节点,表示文件,而 Folder 是容器节点,表示文件夹。容器节点可以包含其他文件和文件夹,从而构建了文件系统的树状结构。
通过组合模式,可以递归地处理文件系统的结构,无论是文件还是文件夹,都可以以相同的方式进行操作。这种模式使得处理复杂的树状结构更加容易。