Java 组合模式(Composite Pattern) 是一种结构型设计模式,主要作用是将对象组合成树形结构,以表示“部分—整体”的层次关系,并让客户端可以统一对待单个对象和组合对象。
下面从“作用”和“典型场景”两方面说明。
interface Component {
void operation();
}
class Leaf implements Component {
public void operation() {
System.out.println("叶子节点");
}
}
class Composite implements Component {
private List<Component> children = new ArrayList<>();
public void add(Component c) { children.add(c); }
public void remove(Component c) { children.remove(c); }
public void operation() {
for (Component c : children) {
c.operation();
}
}
}
客户端:
Component c = new Composite();
c.add(new Leaf());
c.add(new Leaf());
c.operation(); // 统一调用
适合表达如:
if (是组合) else (是单个) 的判断组合结构天然支持递归:
✅ 当你遇到以下情况时使用组合模式:
优点
缺点
Java 组合模式的作用,是用树形结构统一表示“单个对象”和“对象组合”,让客户端以一致方式操作复杂层次结构。
如果你愿意,我也可以给你一个完整可运行的 Java 组合模式示例(如菜单系统或文件系统)。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。