组合模式深度解析:构建灵活树形结构的终极指南
一、组合模式:统一处理简单与复杂对象的艺术
1.1 什么是组合模式?
组合模式(Composite Pattern)是一种结构型设计模式,用于将对象组合成树形结构以表示“部分-整体”的层次关系。核心思想是让客户端以统一的方式处理单个对象和组合对象,就像处理文件系统中的文件夹和文件:
-
叶子节点:文件(无子节点)
-
组合节点:文件夹(可包含文件或子文件夹)
-
统一接口:都支持
ls
命令查看内容
1.2 模式结构UML图
二、文件系统模拟器实战案例 📂
2.1 传统实现的问题
// 硬编码类型判断的客户端代码 public void print(FileSystemNode node) {if (node instanceof File) {System.out.println("文件:" + node.getName());} else if (node instanceof Directory) {Directory dir = (Directory) node;System.out.println("目录:" + dir.getName());for (FileSystemNode child : dir.getChildren()) {print(child); // 递归调用}} }
痛点:客户端需要区分对象类型,违反开闭原则
2.2 组合模式改造方案
步骤1:定义组件接口
public interface FileSystemComponent {void print(String prefix);default void add(FileSystemComponent component) {throw new UnsupportedOperationException();}default void remove(FileSystemComponent component) {throw new UnsupportedOperationException();} }
步骤2:实现叶子节点
public class File implements FileSystemComponent {private St